AXForum  
Вернуться   AXForum > Microsoft Dynamics CRM > Dynamics CRM: Blogs
All
Забыли пароль?
Зарегистрироваться Правила Справка Пользователи Сообщения за день Поиск

 
 
Опции темы Поиск в этой теме Опции просмотра
Старый 04.05.2010, 11:05   #1  
Blog bot is offline
Blog bot
Участник
 
25,584 / 848 (80) +++++++
Регистрация: 28.10.2006
CRM DE LA CREME! Some more useful javascripts for MS CRM
Источник: http://crmdelacreme.blogspot.com/201...me-if-you.html
==============

HI,Like I mentioned I found some more useful scripts on the internet
Enjoy!

Replacing the content of an IFRAME

If you really want to do some funny things in your CRM form, you can create an IFRAME serving as a placeholder for your real HTML code. Create an IFRAME in an entity and name it "IFRAME_TEST". In the Onload event put the following code:
crmForm.all.IFRAME_TEST_d.innerHTML ="Some HTML text";
Note the "_d" at the end of IFRAME_TEST. This single line replaces the whole IFRAME element with your own HTML.

Adding additional values to duration fields
The following script adds the new option "42 Minutes" to the actualdurationminutes field in a task:

var duration = crmForm.all.actualdurationminutesSelect;
var tables = duration.getElementsByTagName("table");
var table = tables[1];var row = table.insertRow();
var newOption = row.insertCell(-1);
var newValue = "42 Minutes";
newOption.setAttribute("val", newValue);
newOption.innerText = newValue;

Changing the title of a CRM form
document.title = "Hello World!";
Changing the Link of a Ticker Symbol from MSN Money to Yahoo Finances
This is an unsupported solution as it requires modifications to server files!
Open the following directory on your CRM server: C:Inetpubwwwroot_formscontrols (may vary depending on your installation)Open the following file: INPUT.text.ticker.htcSearch the following function:

function Launch()
{
if(value.length > 0)
{
Parse();
window.open("http://go.microsoft.com/fwlink?linkid=8506&Symbol=" + encodeURIComponent(value), "", "height=" + (screen.availHeight * .75) + ",width=" + (screen.availWidth * .75) + ,scrollbars=1,resizable=1,status=1,toolbar=1,menubar=1,location=1"); }}
Replace it with the following:
function Launch()
{
if(value.length > 0)
{
Parse();
//window.open("http://go.microsoft.com/fwlink?linkid=8506&Symbol=" + encodeURIComponent(value), "", "height=" + (screen.availHeight * .75) + ",width=" + (screen.availWidth * .75) + ,scrollbars=1,resizable=1,status=1,toolbar=1,menubar=1,location=1");
window.open("http://finance.yahoo.com/q?s=" + encodeURIComponent(value), "", "height=" + (screen.availHeight * .75) + ",width=" + (screen.availWidth * .75) + ",scrollbars=1,resizable=1,status=1,toolbar=1,menubar=1,location=1");
}
}

Save the file.On your client machine: Open Internet Explorer and remove all temporary internet files, so that the new htc source is retrieved. Navigate to any ticker symbol, enter a valid value and double click it.

Counting the number of backslashes in a string

Of course you can use the two code snippets with any character you like.
Solution 1
var text = "hardware\printers\Epson";var paths = text.split("\");alert(paths.length -1);
Solution 2
var text = "hardware\printers\Epson";var numBs = 0;
var index = 0;while(index != -1) { index = text.indexOf("\", index); if (index != -1) { numBs++; index++; }}alert(numBs);

Changing the label of a field at runtime

Lets say you want to change the label of the revenue field, then you simply write

crmForm.all.revenue_c.innerText = "Amount Euro";
Simply append the "_c" to the field name. This should work for most labels.


Changing the colour of a single option in a picklist

You can change the colour and background colour of an option element using the following syntax://TODO: Replace with the schema name of the picklist in question.var list = crmForm.all.;
//using the first option here, you need to find the one you need.var option = list.options[0];
//Set the background colour to red.option.style.backgroundColor = "#FF0000";
//Set the text colour to white.option.style.color = "#FFFFFF";
Opening a new window without the IE menu and status bars

The following is a sample HTML page that you can use to test. Replace the link with the URL of your web page.




Domain









Retrieving the text of a lookup control

var lookup = crmForm.all..DataValue;if (lookup[0] != null) { var theText = lookup[0].name;}

Disabling a form at runtime

document.body.disabled = true;

This will disable all controls except the Notes tab, where you still can enter new notes.

Automatically changing the value of a text field to capitals
Put the following script in the OnChange event of the text field:

crmForm.all..DataValue = crmForm.all..DataValue.toUpperCase();

Getting notified when the user selects a another tab on a form
Put the following in the OnLoad event of your form:

crmForm.all.tab0Tab.onclick = function()
{
alert("Tab 0 clicked");
}
crmForm.all.tab1Tab.onclick = function()
{
alert("Tab 1 clicked");
}

It seems that the tab pages are always named "tabxTab", where x is a number starting from 0 (first tab) to (n-1), where n is the total number of tabs. Maybe you find better events that handle the activation instead of a click, but that's the general way it should work.
The current record id
The primary key is always available in
crmForm.ObjectId
It is set to null, if the record hasn't been saved yet. There are some other useful properties. Look at the "Form Object Model" in the SDK docs for more information.
The current object type code
The type code of the entity being displayed in a CRM form is available through

crmForm.ObjectTypeCode

There are some other useful properties. Look at the "Form Object Model" in the SDK docs for more information.




Initializing a date field with the current date

crmForm.all..DataValue = new Date();
Changing the URL of an IFRAME at runtime

Set the initial URL of the IFRAME to about:blank and execute the following line:

document.all.IFRAME_.src = http://domain/file;
Displaying a picture in a CRM form, using a text field to store the data source

Let's say you have a custom field storing the image name called new_pictureName. Then in the OnLoad event do the following:

if ((crmForm.all.new_pictureName != null) && (crmForm.all.new_pictureName.DataValue != null))
{
document.all.IFRAME_.src = http://server/dir/images/ + crmForm.all.new_pictureName.DataValue;
}

In the OnChange event of the new_pictureName place the following:

if (crmForm.all.new_pictureName.DataValue != null)
{
document.all.IFRAME_.src = http://server/dir/images/ + crmForm.all.new_pictureName.DataValue;
}
else
{
document.all.IFRAME_.src = "about:blank"}

Checking crmForm.all.new_pictureName for null in the OnLoad event is a sanity check. Bulk edit forms will not display all fields and if it is not contained in the form, it will be null. This check is not required in the OnChange event, as this event will never fire if the field does not exist.

Changing the default lookup type

When opening a lookup that can select from multiple entity types, you may want to use a different default entity in the lookup dialog. The following script changes the default entity of the regardingobjectid field in an activity to contacts:
if (crmForm.all.regardingobjectid != null)
{
crmForm.all.regardingobjectid.setAttribute("defaulttype", "2");
}
Checking if a field is present in a form
if (crmForm.all. != null)
{
//do your JavaScript processing here}

You should always check if a field is present before accessing it, because your script may throw an exception if it is not included in a form (like in quick create forms if your field is not required or recommended).
Calculating a date field based upon the selection of a picklist
The following script assumes that you have a picklist with three values: "1 year", "2 years" and "3 years".

var years = 0;
switch(crmForm.all..DataValue)
{
//You need to check the picklist values if they have the values 1, 2 and 3. Look at the attribute in the entity customization and note the option values.
case "1": years = 1;
break;
case "2": years = 2;
break;
case "3": years = 3;
break;
}
if (years != 0)
{
var date = new Date();
date.setYear(date.getYear() + years);
crmForm.all..DataValue = date;
}

Creating a new email when double-clicking a standard text field

if (crmForm.all. != null)
{
crmForm.all..ondblclick = function()
{
var email = crmForm.all..DataValue;
if ((email != null) && (email.length > 0))
{
window.navigate("mailto:" + email);
}
}}
Resetting a field value if validation fails
In the OnLoad event, place the following code:

crmForm.all..setAttribute("lastKnownGood", crmForm.all..DataValue);

This adds a new attribute to field for later access. In the OnChange event put the following:

//checkFailed contains either true or false and must be set to the result of your validation routineif (checkFailed)
{
crmForm.all..DataValue = crmForm.all.fieldToCheck.getAttribute("lastKnownGood");
else
{
crmForm.all..setAttribute("lastKnownGood", crmForm.all.fieldToCheck.DataValue);
}

Inserting line breaks in a text area control
Put the following in the OnLoad event:

crmForm.all..style.whiteSpace = "pre";

Hiding an entire row of a CRM form

//the field you want to hidevar field = crmForm.all.name;//search the enclosing table rowwhile ((field.parentNode != null) && (field.tagName.toLowerCase() != "tr"))
{
field = field.parentNode;
}
//if we found a row, disable itif (field.tagName.toLowerCase() == "tr")
{
field.style.display = "none";
}

Disabling the time selection of a date/time field

You can dynamically enable or disable the time selection box of a date/time field using the following syntax:
var dateField = crmForm.all.;
//Check the existence of the time field. It is null if the control is setup to only display the date.
if (dateField.all.time != null)
{
//Disable the time field
dateField.all.time.disable();
//Enable the time field
dateField.all.time.enable();
}
CRM automatically enables the time selection box if the date value changes to a non-null value, so in order to always disable the time selection box, you need to add the following OnChange event script to the datetime field:
var dateField = crmForm.all.;
//Check the existence of the time field. It is null if the control is setup to only display the date.
if (dateField.all.time != null)
{
//Disable the time field
dateField.all.time.disable();
}
To initially disable the time field, put the following into the form OnLoad event:
var dateField = crmForm.all.;
//Check the existence of the datetime field. It may not be included in a quick create form!
if (dateField != null)
{
//Call the OnChange event handler
dateField.FireOnChange();
}

Changing the time interval in date/time fields

The time selection box of a date/time field uses a 30 minute interval. You can change it to a different interval using the following code in an OnLoad event:

var dateField = crmForm.all.;
//Check the existence of the datetime field. It may not be included in a quick create form!
if (dateField != null)
{
var timeField = dateField.all.time;
//Check the existence of the time field. It is null if the control is setup to only display the date.
if (timeField != null)
{
//The new interval in minutes.
var interval = 15;
var tables = timeField.getElementsByTagName("table");
if ((tables != null) && (tables.length > 0))
{
var table = tables[1];
//Remove all existing values from the selection box while (table.firstChild != null)
{
table.removeChild(table.firstChild);
}
//Add the new values for (hour = 0; hour < 24; hour++)
{
for (min = 0; min < 60; min += interval)
{
var row = table.insertRow();
var cell = row.insertCell();
var time = ((hour < 10) ? "0" : "") + hour + ":" + ((min < 10) ? "0" : "") + min;
cell.setAttribute("val", time);
cell.innerText = time;
}
}
}
}
}

Getting the quote id inside a quotedetail form

There's a hidden field in the quotedetail form storing the quote id. You can access it using
alert("Quote ID = " + crmForm.all.quoteid.DataValue);
How to know which button triggered the OnSave event
You can use the event.Mode property in the OnSave event. It will tell you which button was used to save an entity. Not all values are documented in the SDK, e.g the "Save as completed" in a phone call has a value of 58. As it's not documented, this number may change in future releases.
To get started enter the following into your OnSave script:
alert ("event.Mode = " + event.Mode);
event.returnValue = false;
return false;
This codes makes it impossible to save the entity, but allows you to write down all of the values passed to OnSave. You will see 1 for a normal save operation and 2 for Save and Close. Most but not all constants are defined in /_common/scripts/formevt.js.
Accessing the CRM database from JavaScript
To access the CRM database from JavaScript, use the following as a template:
var connection = new ActiveXObject("ADODB.Connection");
var connectionString = "Provider=SQLOLEDB;Server=xxxxx;Database=xxxx_mscrm;Integrated Security=sspi";
connection.Open(connectionString);
var query = "SELECT name FROM FilteredAccount";
var rs = new ActiveXObject("ADODB.Recordset");
rs.Open(query, connection, /*adOpenKeyset*/1, /*adLockPessimistic*/2);
rs.moveFirst();
var values = "";
while (!rs.eof)
{
values += rs.Fields(0).Value.toString() + " ";
rs.moveNext();
}
connection.Close();
alert(values);
You may need to adjust your security settings in IE in order to run this code.

Modifying the Quick Create Form

Allthough the quick create form isn't listed in the forms and views dialog, it uses the same scripts entered in the main application form. You can use the following in the OnLoad script to run code when inside of a quick create form:

if (crmForm.FormType == 5 /* Quick Create Form */)
{
//modify the form using DHTML
}
Forcing the selection of an account in the potential customer field of an opportunity
Put the following into the opportunity's OnLoad event:
crmForm.all.customerid.setAttribute("lookuptypes", "1");
This tells the customer lookup to only include the account (object type code 1). A value of 2 forces the lookup to only display contacts.


Hiding and showing fields dynamically based on other field values

You can do this in client-side JavaScript. Let's say you have a picklist named "new_category" and you have assigned the following options to it:
1 – Business
2 – Private
3 - Unspecified
Let's further assume that you want to hide the fields "new_a" and "new_b" whenever a user selects "Private", but they should be visible if a different option is selected in the picklist. Your OnChange event script of the new_category field will be:

var hideValues = (crmForm.all.new_category != null) && (crmForm.all.new_category.DataValue == "2");
var displayStyle = hideValues ? "none" : "";
crmForm.all.new_a.style.display = displayStyle;
crmForm.all.new_b.style.display = displayStyle;

To run the code when the form is initially loaded, put the following into the OnLoad event:

if (crmForm.all.new_category != null)
{
crmForm.all.new_category.FireOnChange();
}
The test for a null value of crmForm.all.new_category is included to avoid errors if the field is not available on a form. This is true for quick create forms if the field required level is not set to business required or business recommended.
Removing the value from a lookup field
crmForm.all..DataValue = null;
Hiding tabs at runtime
You can hide and show entire tabs dynamically using the following code:
//Add your condition here, usually a field comparison in an OnChange event
if (condition == true)
{
//hide the second tab
crmForm.all.tab1Tab.style.display = "none";
}
else
{
//show the second tab
crmForm.all.tab1Tab.style.display = "";
}
The tabs are named "tab0Tab", "tab1Tab", "tab2Tab" and so on.

Setting the active tab

From the SDK docs:SetFocus: Sets the focus, changes tabs, and scrolls the window as necessary to show the specified field. Example:
// Set focus to the field.
crmForm.all.SOME_FIELD_ID.SetFocus();

Displaying related entities instead of the form when opening a record

To open a related entity view of the left navigation bar (like contacts in an account entity), you can use the following:
loadArea("areaContacts");
Each entry in the navigation bar has a unique area name (areaContacts is just a sample). If you haven't already done it, download and install the Internet Explorer Developer Toolbar to find the name of the entry you're after. Some instructions on how to use it are in http://www.stunnware.com/crm2/topic....mLookAndFeel1; though it is a different topic, I included some screenshots using the developer toolbar in CRM.

Modifying the color of disabled form fields

Disabled form fields are sometimes hard to read. Making the color a little bit darker greatly helps to read all of the content without loosing the information that a field is read-only.
Open the following file in your CRM web: /_forms/controls/controls.css. Then find the following style:
INPUT.ro,TEXTAREA.ro,DIV.ro,SPAN.ro
{
background-color: #ffffff;
color: #808080;
border-color: #808080;
}
The color attribute is the light gray you're seeing by default. You may change it to #404040 to get a slightly darker gray. If you don't see the new colors in IE, hit CTRL-F5 to reload the source files, including the updated css file.
Removing a navigation bar entry at runtime
To remove a navigation bar entry dynamically, you can use the following code:
var navigationBarEntry = document.getElementById("navProds");
if (navigationBarEntry != null)
{
var lbArea = navigationBarEntry.parentNode;
if (lbArea != null)
{
lbArea.removeChild(navigationBarEntry);
}
}
If you haven't already done it, download and install the Internet Explorer Developer Toolbar to find the name of the navigation bar entry.

Changing the colour of a label

var label = crmForm.all._c;
label.innerHTML = "" + label.innerText + "";

<span style="font-family:arial;">
Hide a section on a form
crmForm.all.new_attribute_c.parentElement.parentElement.parentElement.style.display = 'none'


To show the section again:
crmForm.all.new_attribute_c.parentElement.parentElement.parentElement.style.display = 'block'

AJAX - CRM 3 only
checkResult = function()
{
var oXmlDoc = new ActiveXObject("Microsoft.XMLDOM");
oXmlDoc.async = false;
var s;
s = "http://localhost:5555/adv_postback.aspx?fundid=" + crmForm.all.adv_fundid.DataValue[0].id;
oXmlDoc.load(s);
var oNode = oXmlDoc.selectSingleNode("results/fundcode");
if (oNode != null)
{
res = oNode.text;
crmForm.all.adv_adminno.DataValue = res
}
}
Maximise Screen
if (window.screen)
{
var aw = screen.availWidth;
var ah = screen.availHeight;
window.moveTo(0, 0);
window.resizeTo(aw, ah);
}
Date Functions
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" + year)
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10)
minutes = "0" + minutes
document.write(hours + ":" + minutes + " ")
if(hours > 11)
{
document.write("PM")
}
else
{
document.write("AM")
}
getTime() - Number of milliseconds since 1/1/1970 @ 12:00 AM
getSeconds() - Number of seconds (0-59)
getMinutes() - Number of minutes (0-59)
getHours() - Number of hours (0-23)
getDay() - Day of the week(0-6). 0 = Sunday, ... , 6 = Saturday
getDate() - Day of the month (0-31)
getMonth() - Number of month (0-11)
getFullYear() - The four digit year (1970-9999)
MAKE THE RECIPIENT BLANK FOR NEW EMAILS
var CRM_CREATE_FORM = 1;
var formType = crmForm.FormType;
if(formType == CRM_CREATE_FORM)
{
crmForm.all.to.DataValue = null;
}

FORMAT PHONE NUMBER


// Attempt to auto-format basic US phone numbers. This method supports
// 7 and 10 digit numbers. Example: (410) 555-1212
// Get the field that fired the event
var oField = event.srcElement;
// If we have the field and all is well
if (typeof(oField) != "undefined" && oField != null)
{
// Remove any non-numeric characters
var sTmp = oField.DataValue.replace(/[^0-9]/g, "");
// If the number is a length we expect and support, format the number
switch (sTmp.length)
{
case "4105551212".length:
oField.DataValue = "(" + sTmp.substr(0, 3) + ") " + sTmp.substr(3, 3) + "-" + sTmp.substr(6, 4);
break;
case "5551212".length:
oField.DataValue = sTmp.substr(0, 3) + "-" + sTmp.substr(3, 4);
break;
}
}


CONFIRM SAVE


if (confirm("Are you sure you want to save this Stakeholder Contact?"))
{
//save the form.
}
else
{
event.returnValue = false;
validationErrors = true;
}



HIDE CONVERT BUTTON ON LEAD


var myField = crmForm.all.leadqualitycode.DataValue;
switch(crmForm.FormType)
{
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
break;
case 2:
if(myField == [ValueThatEqualsYes])
{
var btConvert = "_MBconvertLead";
var menuButton = document.getElementById(btConvert);
if (menuButton != null)
{
menuButton.style.display='';
}
}
else
{
var btConvert = "_MBconvertLead";
var menuButton = document.getElementById(btConvert);
if (menuButton != null)
{
menuButton.style.display='none';
}
}
break;
}


MAKE THE TAB TITLE BLUE

crmForm.all.tab0Tab.style.backgroundColor="blue";

SHOW NUMBER OF NOTES ON THE NOTES TAB (CRM 3)
This is in the form load event of the aspx page:
Dim NoteCount As Integer, ID As String, SQL As String, _ con As SqlConnection, com As SqlCommand, ds As New DataSet
ID = Request("ID")
SQL = "Select count(*) from annotation where ObjectID='" + ID + "'"
con = New SqlConnection
con.ConnectionString = "server=galatea;database=IOM_MSCRM;User Id=crmcustom;Password=crm@custom;"
con.Open()
com = New SqlCommand
com.CommandText = SQL
com.Connection = con
Dim da As New SqlDataAdapter(com)
da.Fill(ds)
For Each dr As DataRow In ds.Tables(0).Rows
NoteCount = dr.Item(0)
Next
con.Close()
Response.Clear()
Response.ContentType = "textXML"
Response.Write("" & NoteCount & "")
Response.End()
This is in the form load event of the CMR form:
DISPLAY NUMBER OF NOTES
var oXmlDoc = new ActiveXObject("Microsoft.XMLDOM");
oXmlDoc.async = false; // We want to wait for a response
var site;
site = window.location.protocol + "//" + window.location.host + "/ISP_IOM/CountNotes.aspx?id=" + crmForm.ObjectId
oXmlDoc.load(site);
var oNode = oXmlDoc.selectSingleNode("results/result");
if (oNode != null)
{
res = oNode.text;
crmForm.all.tab3Tab.innerText = "Notes (" + res + ")";
}


CHECK FOR . IN STRING


if (myString.indexOf(".")>=0)
{
alert("yes!");
}
else
{
alert("no!");
}
window.alert('demoalert');


Buttons
This is an example on how to create a button on the form, using java script. First of all we need to create a nvarchar attribute and put it on the form where we want our button. I assume that everybody knows how to create an attribute and put in on the form, so i won't talk about this.
In this example my attribute's schema name is new_button. Here is the code:
// This is how we call the button, what we see
crmForm.all.new_button.DataValue = "Ok";
// We could align it a bit
crmForm.all.new_button.style.textAlign = "center";
crmForm.all.new_button.vAlign = "middle";
//we make the mouse look as a hand when we're moving over
crmForm.all.new_button.style.cursor = "hand";
crmForm.all.new_button.style.backgroundColor = "#CADFFC";
crmForm.all.new_button.style.color = "#FF0000";
crmForm.all.new_button.style.borderColor = "#330066";
crmForm.all.new_button.style.fontWeight = "bold";
crmForm.all.new_button.contentEditable = false;
//we attach some events in order to make it look nice :)
crmForm.all.new_button.attachEvent("onmousedown",color1);
crmForm.all.new_button.attachEvent("onmouseup",color2);
crmForm.all.new_button.attachEvent("onmouseover",color3);
crmForm.all.new_button.attachEvent("onmouseleave",color4);
function color3()
{
crmForm.all.new_button.style.backgroundColor = "#6699FF";
}
function color4()
{
crmForm.all.new_button.style.backgroundColor = "CADFFC";
}
function color1()
{
crmForm.all.new_button.style.color = "000099";
}
function color2()
{
crmForm.all.new_button.style.color = "FF0000";
}
//here we attach what we want our button do
crmForm.all.new_button.attachEvent("onclick",someFunction);



Integer Validation
This script Validates weather an entry is an integer field or not using the isNAN function
var my_string= crmForm.all.new_accountnumber.DataValue
if(isNaN(my_string))
{
alert ("Please do not enter text into the account number field");
event.returnValue = false;
}
else
{alert("Account Number Accepted ");
if (crmForm.all.new_accountnumber.DataValue.length != 11)
{
alert ("Please enter in a numeric account number that is 11 digits long");
event.returnValue = false;
}
}

Replacing the content of an IFRAME
If you really want to do some funny things in your CRM form, you can create an IFRAME serving as a placeholder for your real HTML code. Create an IFRAME in an entity and name it "IFRAME_TEST". In the Onload event put the following code:
crmForm.all.IFRAME_TEST_d.innerHTML ="Some HTML text";
Note the "_d" at the end of IFRAME_TEST. This single line replaces the whole IFRAME element with your own HTML.
Adding additional values to duration fields
The following script adds the new option "42 Minutes" to the actualdurationminutes field in a task:
var duration = crmForm.all.actualdurationminutesSelect;

var tables = duration.getElementsByTagName("table");
var table = tables[1];

var row = table.insertRow();
var newOption = row.insertCell(-1);

var newValue = "42 Minutes";
newOption.setAttribute("val", newValue);
newOption.innerText = newValue;


Changing the title of a CRM form
document.title = "Hello World!";


Changing the Link of a Ticker Symbol from MSN Money to Yahoo Finances
This is an unsupported solution as it requires modifications to server files!
Open the following directory on your CRM server: C:Inetpubwwwroot_formscontrols (may vary depending on your installation)
Open the following file: INPUT.text.ticker.htc

Search the following function:
function Launch()
{
if(value.length > 0)
{
Parse();

window.open("http://go.microsoft.com/fwlink?linkid=8506&Symbol=" +
encodeURIComponent(value), "", "height=" + (screen.availHeight * .75) +
",width=" + (screen.availWidth * .75) +
,scrollbars=1,resizable=1,status=1,toolbar=1,menubar=1,location=1");
}
}
Replace it with the following:
function Launch()
{
if(value.length > 0)
{
Parse();

//window.open("http://go.microsoft.com/fwlink?linkid=8506&Symbol=" +
encodeURIComponent(value), "", "height=" + (screen.availHeight * .75) +
",width=" + (screen.availWidth * .75) +
,scrollbars=1,resizable=1,status=1,toolbar=1,menubar=1,location=1");
window.open("http://finance.yahoo.com/q?s=" +
encodeURIComponent(value), "", "height=" + (screen.availHeight * .75) +
",width=" + (screen.availWidth * .75) +
",scrollbars=1,resizable=1,status=1,toolbar=1,menubar=1,location=1");
}
}
Save the file.

On your client machine: Open Internet Explorer and remove all temporary internet files, so that the new htc source is retrieved. Navigate to any ticker symbol, enter a valid value and double click it.


Counting the number of backslashes in a string
Of course you can use the two code snippets with any character you like.
Solution 1
var text = "hardware\printers\Epson";
var paths = text.split("\");
alert(paths.length -1);
Solution 2)
var text = "hardware\printers\Epson";
var numBs = 0;
var index = 0;

while(index != -1) {
index = text.indexOf("\", index);

if (index != -1) {
numBs++;
index++;
}
}

alert(numBs);


Changing the label of a field at runtime
Lets say you want to change the label of the revenue field, then you simply write
crmForm.all.revenue_c.innerText = "Amount Euro";
Simply append the "_c" to the field name. This should work for most labels.


Changing the color of a single option in a picklist
You can change the color and background color of an option element using the following syntax:

//TODO: Replace with the schema name of the picklist in question.
var list = crmForm.all.;

//using the first option here, you need to find the one you need.
var option = list.options[0];

//Set the background color to red.
option.style.backgroundColor = "#FF0000";

//Set the text color to white.
option.style.color = "#FFFFFF";
Opening a new window without the IE menu and status bars
The following is a sample HTML page that you can use to test. Replace the link with the URL of your web page.




Stunnware





Retrieving the text of a lookup control
var lookup = crmForm.all..DataValue;

if (lookup[0] != null) {
var theText = lookup[0].name;
}


Disabling a form at runtime
document.body.disabled = true;
This will disable all controls except the Notes tab, where you still can
enter new notes.


Automatically changing the value of a text field to capitals
Put the following script in the OnChange event of the text field:
crmForm.all..DataValue = crmForm.all..DataValue.toUpperCase();


Getting notified when the user selects a another tab on a form
Put the following in the OnLoad event of your form:
crmForm.all.tab0Tab.onclick = function() {
alert("Tab 0 clicked");
}

crmForm.all.tab1Tab.onclick = function() {
alert("Tab 1 clicked");
}
It seems that the tab pages are always named "tabxTab", where x is a number starting from 0 (first tab) to (n-1), where n is the total number of tabs. Maybe you find better events that handle the activation instead of a click, but that's the general way it should work.
The current record id
The primary key is always available in
crmForm.ObjectId
It is set to null, if the record hasn't been saved yet. There are some other useful properties. Look at the "Form Object Model" in the SDK docs for more information.
The current object type code
The type code of the entity being displayed in a CRM form is available through
crmForm.ObjectTypeCode
There are some other useful properties. Look at the "Form Object Model" in the SDK docs for more information.


Initializing a date field with the current date
crmForm.all..DataValue = new Date();


Changing the URL of an IFRAME at runtime
Set the initial URL of the IFRAME to about:blank and execute the following line:
document.all.IFRAME_.src = http://domain/file;


Displaying a picture in a CRM form, using a text field to store the data source
Let's say you have a custom field storing the image name called new_pictureName. Then in
the OnLoad event do the following:
if ((crmForm.all.new_pictureName != null) && (crmForm.all.new_pictureName.DataValue != null)) {
document.all.IFRAME_.src = http://server/dir/images/ + crmForm.all.new_pictureName.DataValue;
}
In the OnChange event of the new_pictureName place the following:
if (crmForm.all.new_pictureName.DataValue != null) {
document.all.IFRAME_.src = http://server/dir/images/ +
crmForm.all.new_pictureName.DataValue;
}

else {
document.all.IFRAME_.src = "about:blank"
}
Checking crmForm.all.new_pictureName for null in the OnLoad event is a sanity check. Bulk edit forms will not display all fields and if it is not contained in the form, it will be null. This check is not required in the OnChange event, as this event will never fire if the field does not exist.


Changing the default lookup type
When opening a lookup that can select from multiple entity types, you may want to use a different default entity in the lookup dialog. The following script changes the default entity of the regardingobjectid field in an activity to contacts:
if (crmForm.all.regardingobjectid != null) {
crmForm.all.regardingobjectid.setAttribute("defaulttype", "2");
}
Checking if a field is present in a form
if (crmForm.all. != null) {
//do your JavaScript processing here
}
You should always check if a field is present before accessing it, because your script may throw an exception if it is not included in a form (like in quick create forms if your field is not required or recommended).


Calculating a date field based upon the selection of a picklist
The following script assumes that you have a picklist with three values: "1 year", "2 years" and "3 years".
var years = 0;

switch(crmForm.all..DataValue) {

//You need to check the picklist values if they have the values 1, 2 and 3. Look at the attribute in the entity customization and note the option values.
case "1":
years = 1;
break;

case "2":
years = 2;
break;

case "3":
years = 3;
break;
}

if (years != 0) {

var date = new Date();
date.setYear(date.getYear() + years);

crmForm.all..DataValue = date;
}
Creating a new email when double-clicking a standard text field
if (crmForm.all. != null) {

crmForm.all..ondblclick = function() {

var email = crmForm.all..DataValue;

if ((email != null) && (email.length > 0)) {
window.navigate("mailto:" + email);
}
}
}


Resetting a field value if validation fails
In the OnLoad event, place the following code:
crmForm.all..setAttribute("lastKnownGood", crmForm.all..DataValue);
This adds a new attribute to field for later access. In the OnChange event put the following:
//checkFailed contains either true or false and must be set to the result of your validation routine
if (checkFailed) {
crmForm.all..DataValue = crmForm.all.fieldToCheck.getAttribute("lastKnownGood");
}

else {
crmForm.all..setAttribute("lastKnownGood", crmForm.all.fieldToCheck.DataValue);
}


Inserting line breaks in a text area control
Put the following in the OnLoad event:
crmForm.all..style.whiteSpace = "pre";


Hiding an entire row of a CRM form
//the field you want to hide
var field = crmForm.all.name;

//search the enclosing table row
while ((field.parentNode != null) && (field.tagName.toLowerCase() != "tr")) {
field = field.parentNode;
}

//if we found a row, disable it
if (field.tagName.toLowerCase() == "tr") {
field.style.display = "none";
}
It's been a while since I posted these small JavaScript snippets (More JavaScript Code, More JavaScript Code Part 2), so after half a year I'm adding the third part today, containing 23 new samples. Hope you find it as useful as the first two articles.


Setting the background color of a CRM form
If you want to make it easier for a user to note what type of entity a CRM form is displaying, you can change the background color with only one line of code:
document.body.style.backgroundColor = 'red';
Put it into the OnLoad event of the form you want to change and replace 'red' with the color of your choice.
Why can't we use VBScript to write client-side code?
As CRM is a web application, client-side code deals with DHTML objects and the supported languages in IE are JavaScript and VBScript. JavaScript is the standard used in the internet, while VBScript is IE only, so it will never work with any browser other than IE.
One could argue that CRM is tied to IE6 and above, but allowing and supporting VBScript would make it impossible for the product team to even think about supporting other browsers. I never saw an official statement as to why VBScript is not supported though.
Some calculated fields on the CRM form are not saved in the database
If the field is disabled, which is a common practice for calculated fields, it is not sent to the server when the form is saved. To override this behavior, add this line to your code:
crmForm.all.your_field.ForceSubmit = true;


Changing detailed tooltips when hovering over fields in a CRM form
This article explains in depth how to do it: http://blogs.msdn.com/crm/archive/20...tive-help.aspx
Fixing problems with orphaned OnChange event handlers
When changing entire field definitions in client-side script (e.g. Overcoming relationship restrictions in Microsoft CRM v3.0 or Converting the country field to a combobox) the OnChange event code may not be triggered.
To overcome this situation, place the following in your script after you have replaced the HTML code:
crmForm.all.your_field.onchange = function() {
//add code here
}
If you need to initially call the OnChange code, use this instead:
your_field_OnChange = function() {
//add code here
}

//attaching the event
crmForm.all.your_field.onchange = your_field_OnChange;

//calling the event (same idea as FireOnChange())
your_field_OnChange();


Setting the field required level at runtime
You can access the current required level of any field by using the RequiredLevel property:
var reqLevel = crmForm.all.your_Field.RequiredLevel.
However, as it is a read-only property, you cannot use it to change the required level. There is an undocumented (and therefore unsupported) method on the crmForm object allowing to make a field required or not required:
function SetFieldReqLevel(sField, bRequired)
If bRequired is set to 0 (false), it is not required. If bRequired is set to anything else (true), the field is required.
Note: you cannot use this method to make a field business recommended. Here's the code to set a field to any of the possible states:
//No Requirement
//------------------------------
crmForm.all.your_field.setAttribute("req", 0);
crmForm.all.your_field_c.className = "n";

//Recommended
//------------------------------
crmForm.all.your_field.setAttribute("req", 1);
crmForm.all.your_field_c.className = "rec";

//Required
//------------------------------
crmForm.all.your_field.setAttribute("req", 2);
crmForm.all.your_field_c.className = "req";
Replace "your_field" and "your_field_c" with the name of the field you want to set, e.g. to set the accountnumber field to business recommended, you specify
crmForm.all.accountnumber.setAttribute("req", 1);
crmForm.all.accountnumber_c.className = "rec";
Setting a default time in a date field
A date field in a CRM form always contains a date part and optionally a time part. Sometimes it is useful to set a default time, like 8:30am, but unless the user has entered a valid date, the time selection box is disabled. Here's the code to set the default time once the user has specified the date part:
OnLoad
----------------------------------------
//check if the field exists on the form
if (crmForm.all.your_DateField != null) {
//save the value for future reference. Note that it is a global variable.
_previousValue = crmForm.all.your_DateField.DataValue;
}
OnChange of your date field
----------------------------------------
var dateField = crmForm.all.your_DateField;
var currentValue = dateField.DataValue;

//If the user changes the date field from null to a valid date, set the
//time portion to 8:30
if ((currentValue != null) && (_previousValue == null)) {
dateField.DataValue = new Date(currentValue.getYear(), currentValue.getMonth(), currentValue.getDate(), 8, 30);
}

//update _previousValue
_previousValue = currentValue;
I tried it with the scheduledend field of a task and it worked. The time combo of the scheduledend field is disabled as long as you put a date into the date field. This triggers the OnChange event and sets the default time.
User interaction with yes/no style message boxes
You can use window.confirm to present the user a yes/no-style dialog. The buttons are actually named "Ok" and "Cancel", so you have to use a good explanation in the message text. The result is either true (Ok) or false (Cancel):
var answer = window.confirm("Click Ok to proceed or Cancel to abort the operation.");

if (answer) {
//User selected OK
}

else {
//User selected Cancel
}
Testing if a lookup field has a value
It's the same as as for any other field type:
if (crmForm.all.your_field.DataValue == null) {
//code here
}


Comparing date values
It is a common mistake to directly compare two date values like this:
var date1 = new Date(2007, 4, 30);
var date2 = new Date(2007, 5, 1);

if (date1 > date2) {
//some code here
}
You may expect it to work, but you have to use the valueOf method of the Date object:
var date1 = new Date(2007, 4, 30);
var date2 = new Date(2007, 5, 1);

if (date1.valueOf() > date2.valueOf()) {
//some code here
}


Getting notified when the user enters a form field
The OnChange event of a form field is fired when you are leaving a field (and of course have changed the field value). If you want to perform an action when the users enters the field, use the onfocus event:
crmForm.all.your_field.onfocusin = function() {
alert("Received focus");
}


Overriding the click event of a lookup field
If you need to run code whenever a user clicks on a lookup button, use the following code to override the standard implementation of the click event:
//overrides the default click handler
crmForm.all.your_lookupField.onclick = function() {

alert("Lookup dialog is opening now");

//open the lookup dialog
crmForm.all.your_lookupField.Lookup(true);

alert("Lookup dialog closed");
}
Be careful with this as some lookup fields specify additional settings in their click events.
Formatting a date to YYYYMMDD
There is no toString() implementation in JavaScript allowing you to format a data value, so you have to build it on your own:
getYear returns the current year
getMonth returns the month starting from 0 for January to 11 for December
getDate returns the day of the month (1-31)
A common error is to use getDay instead of getDate. getDate returns the day of the week.
var now = new Date();

var year = now.getYear().toString();
var month = (now.getMonth() + 1).toString();
var dayOfMonth = now.getDate().toString();

if (month.length == 1) {
month = "0" + month;
}

if (dayOfMonth.length == 1) {
dayOfMonth = "0" + dayOfMonth;
}

var yyyymmdd = year + month + dayOfMonth;
The DataValue of a picklist is a string!
The DataValue of a picklist is a string, not an integer. You would expect it to be an integer as a picklist value is stored as an integer in the database and the Picklist class in the WSDL also specifies an integer value. Anyway when comparing the value of a picklist in client-side code, make sure to use a string value:
if (crmForm.all.your_picklist.DataValue == "1") {
}


Setting a picklist's default value in code
If a default option is specified in the attribute definition of a picklist, CRM assumes that you don't want to allow an empty value. This may not be true in all circumstances, so here's the workaround: In the attribute definition change the default value back to unassigned. This adds back the empty option in the picklist. Open the form's OnLoad event and add the following code:
if (crmForm.ObjectId == null) {
crmForm.all.your_picklist.DataValue = "1";
}
The code selects the first option in the picklist when inside a create form. It does not change the value once the form has been saved.
Starting an application from a CRM form
var shell = new ActiveXObject("WScript.Shell");

if (shell != null) {
shell.Run("c:\directory\application.exe " + crmForm.ObjectId);
}
You may face security issues preventing your code from being executed. An alternative is to use a custom .NET assembly as outlined in Using .NET assemblies in JavaScript code.


Changing the available entity types in a lookup dialog
Use one of the following in your OnLoad event:
//Allow only accounts to be selected
crmForm.all.regardingobjectid.setAttribute("lookuptypes", "1");

//Allow only contacts to be selected
crmForm.all.regardingobjectid.setAttribute("lookuptypes", "2");

//Allow accounts or contacts to be selected
crmForm.all.regardingobjectid.setAttribute("lookuptypes", "1,2");
It does not change the behavior of the form assistant, but the lookup dialog will not display any other entity. The attribute values are entity type codes and are documented in the SDK help file. You can use the code for any field allowing multiple entity types (usually customer fields and the regarding field).
Setting the text of the "Save As Completed" button
To display the text "Save as completed" in the toolbar button performing this action, put this code into the OnLoad event:
document.all._MBSaveAsCompleted.children[0].innerHTML += "Save as completed";
This is unsupported and may not work in the future.


Calculating durations
The following code subtracts the current date from a date specified on a CRM form and calculates the remaining or elapsed days, hours or minutes.
var displayField = crmForm.all.;
var formDate = crmForm.all..DataValue;
var now = new Date();
var ms = formDate.valueOf() - now.valueOf();
var minutes = ms / 1000 / 60;
var hours = minutes / 60;
var days = hours / 24;

if (days >= 1) {
displayField.DataValue = Math.floor(days) + " day(s) left";
}

else if (hours >= 1) {
displayField.DataValue = Math.floor(hours) + " hour(s) left";
}

else if (minutes >= 1) {
displayField.DataValue = Math.floor(minutes) + " minute(s) left";
}

else if (days 0)) {

var table = tables[1];

//Remove all existing values from the selection box
while (table.firstChild != null) {
table.removeChild(table.firstChild);
}

//Add the new values
for (hour = 0; hour < 24; hour++) {
for (min = 0; min < 60; min += interval) {

var row = table.insertRow();
var cell = row.insertCell();
var time = ((hour < 10) ? "0" : "") + hour + ":" + ((min < 10) ? "0" : "") + min;

cell.setAttribute("val", time);
cell.innerText = time;
}
}
}
}
}


Getting the quote id inside a quotedetail form
There's a hidden field in the quotedetail form storing the quote id. You can access it using
alert("Quote ID = " + crmForm.all.quoteid.DataValue);


How to know which button triggered the OnSave event
You can use the event.Mode property in the OnSave event. It will tell you which button was used to save an entity. Not all values are documented in the SDK, e.g the "Save as completed" in a phone call has a value of 58. As it's not documented, this number may change in future releases.
To get started enter the following into your OnSave script:
alert ("event.Mode = " + event.Mode);
event.returnValue = false;
return false;
This codes makes it impossible to save the entity, but allows you to write down all of the values passed to OnSave. You will see 1 for a normal save operation and 2 for Save and Close. Most but not all constants are defined in /_common/scripts/formevt.js.


Accessing the CRM database from JavaScript
To access the CRM database from JavaScript, use the following as a template:
var connection = new ActiveXObject("ADODB.Connection");
var connectionString = "Provider=SQLOLEDB;Server=STUNNWARECRM;Database=stunnware_mscrm;Integrated Security=sspi";

connection.Open(connectionString);

var query = "SELECT name FROM FilteredAccount";
var rs = new ActiveXObject("ADODB.Recordset");

rs.Open(query, connection, /*adOpenKeyset*/1, /*adLockPessimistic*/2);
rs.moveFirst();

var values = "";

while (!rs.eof) {
values += rs.Fields(0).Value.toString() + " ";
rs.moveNext();
}

connection.Close();

alert(values);
You may need to adjust your security settings in IE in order to run this code.


Modifying the Quick Create Form
Allthough the quick create form isn't listed in the forms and views dialog, it uses the same scripts entered in the main application form. You can use the following in the OnLoad script to run code when inside of a quick create form:
if (crmForm.FormType == 5 /* Quick Create Form */) {
//modify the form using DHTML
}


Forcing the selection of an account in the potential customer field of an opportunity
Put the following into the opportunity's OnLoad event:
crmForm.all.customerid.setAttribute("lookuptypes", "1");
This tells the customer lookup to only include the account (object type code 1). A value of 2 forces the lookup to only display contacts.


Hiding and showing fields dynamically based on other field values
You can do this in client-side JavaScript. Let's say you have a picklist named "new_category" and you have assigned the following options to it:
1 - Business
2 - Private
3 - Unspecified
Let's further assume that you want to hide the fields "new_a" and "new_b" whenever a user selects "Private", but they should be visible if a different option is selected in the picklist. Your OnChange event script of the new_category field will be:
var hideValues = (crmForm.all.new_category != null) && (crmForm.all.new_category.DataValue == "2");
var displayStyle = hideValues ? "none" : "";

crmForm.all.new_a.style.display = displayStyle;
crmForm.all.new_b.style.display = displayStyle;
To run the code when the form is initially loaded, put the following into the OnLoad event:
if (crmForm.all.new_category != null) {
crmForm.all.new_category.FireOnChange();
}
The test for a null value of crmForm.all.new_category is included to avoid errors if the field is not available on a form. This is true for quick create forms if the field required level is not set to business required or business recommended.


Removing the value from a lookup field
crmForm.all..DataValue = null;


Hiding tabs at runtime
You can hide and show entire tabs dynamically using the following code:
//Add your condition here, usually a field comparison in an OnChange event
if (condition == true) {
//hide the second tab
crmForm.all.tab1Tab.style.display = "none";
}

else {
//show the second tab
crmForm.all.tab1Tab.style.display = "";
}
The tabs are named "tab0Tab", "tab1Tab", "tab2Tab" and so on.


Setting the active tab
From the SDK docs:
SetFocus: Sets the focus, changes tabs, and scrolls the window as necessary to show the specified field. Example:
// Set focus to the field.
crmForm.all.SOME_FIELD_ID.SetFocus();


Displaying related entities instead of the form when opening a record
To open a related entity view of the left navigation bar (like contacts in an account entity), you can use the following:
loadArea("areaContacts");
Each entry in the navigation bar has a unique area name (areaContacts is just a sample). If you haven't already done it, download and install the Internet Explorer Developer Toolbar to find the name of the entry you're after. Some instructions on how to use it are in http://www.stunnware.com/crm2/topic....mLookAndFeel1; though it is a different topic, I included some screenshots using the developer toolbar in CRM.


Modifying the color of disabled form fields
Disabled form fields are sometimes hard to read. Making the color a little bit darker greatly helps to read all of the content without loosing the information that a field is read-only.
Open the following file in your CRM web: /_forms/controls/controls.css. Then find the following style:
INPUT.ro,TEXTAREA.ro,DIV.ro,SPAN.ro
{
background-color: #ffffff;
color: #808080;
border-color: #808080;
}
The color attribute is the light gray you're seeing by default. You may change it to #404040 to get a slightly darker gray. If you don't see the new colors in IE, hit CTRL-F5 to reload the source files, including the updated css file.


Removing a navigation bar entry at runtime
To remove a navigation bar entry dynamically, you can use the following code:
var navigationBarEntry = document.getElementById("navProds");

if (navigationBarEntry != null) {

var lbArea = navigationBarEntry.parentNode;

if (lbArea != null) {
lbArea.removeChild(navigationBarEntry);
}
}
If you haven't already done it, download and install the Internet Explorer Developer Toolbar to find the name of the navigation bar entry.


Changing the color of a label
var label = crmForm.all._c;
label.innerHTML = "" + label.innerText + "";
It's time to continue the "More JavaScript" series. Here's the fifth article containing more snippets and I hope that you find them as valuable as the four previous articles. I also updated the JavaScript Snippets Directory.


Formatting international phone numbers
The CRM SDK contains a sample to format US phone numbers and it works pretty well. However, there are customers outside the US and the sample doesn't work with international phone numbers. An easy formatting rule is replacing any occurrence of '(', ')' or a space with a dash. People can then enter the phone number in their preferred way, but get the same output.
var originalPhoneNumber = "+49 (89) 12345678";
var formattedPhoneNumber = originalPhoneNumber.replace(/[^0-9,+]/g, "-");
formattedPhoneNumber = formattedPhoneNumber.replace(/-+/g, "-");
alert(formattedPhoneNumber);
The first call to the replace method changes every character in the input string that is not a digit and not the plus sign (which is used for international
numbers) to the dash symbol. However, the output is +49--89--12345678, so the second call replaces all occurrences of multiple dashes with a single
one, giving a final result of +49-89-12345678.


Rounding numerical fields
Rounding fields is done similar to any other programming language. The following method rounds a float value using a precision of two decimal places:
function round(value) {
return Math.round(value * 100) / 100;
}
The Math object defines three methods for rounding operations:
• Math.ceil(arg): Returns an integer value equal to the smallest integer greater than or equal to its numeric argument.
• Math.floor(arg): Returns an integer value equal to the greatest integer less than or equal to its numeric argument.
• Math.round(arg): If the decimal portion of number is 0.5 or greater, the return value is equal to the smallest integer greater than number. Otherwise, round returns the largest integer less than or equal to number.
Be aware of null values in Boolean fields
When working with Boolean fields it's seems natural to compare the value to either true or false:
var value = crmForm.all.my_bool.DataValue;

if (value == true) {
//do something
}

else {
//do something else
}
However, the value may also be null and you should make sure that your code handles it correctly:
var value = crmForm.all.my_bool.DataValue;

if (value == null) {
//do appropriate steps if there is no value
}

else if (value == true) {
//do something
}

else {
//do something else
}
If you want to execute either the "true" part or the "false" part when no value is set, then I recommended the following (including the comment, to make it obvious):
var value = crmForm.all.my_bool.DataValue;

//Default to true if no value is set
if (value == null) {
value = true;
}

if (value == true) {
//do something
}

else {
//do something else
}
Reusing code in OnLoad and OnChange event handlers
I often see code like this:
OnLoad:
if (crmForm.all.my_lookup_field.DataValue != null) {
crmForm.all.my_text_field.DataValue = crmForm.all.my_lookup_field.DataValue[0].name;
}
OnChange:
if (crmForm.all.my_lookup_field.DataValue != null) {
crmForm.all.my_text_field.DataValue = crmForm.all.my_lookup_field.DataValue[0].name;
}
The code is identical in both events: it copies the display name of the selected item in a lookup field to a text box. Later you notice that it doesn't remove an existing value in the text field when the user removes the lookup selection and change the OnChange code to this:
if (crmForm.all.my_lookup_field.DataValue != null) {
crmForm.all.my_text_field.DataValue = crmForm.all.my_lookup_field.DataValue[0].name;
}

else {
crmForm.all.my_text_field.DataValue = null;
}
It sometimes happens that you forget to change the OnLoad code as well, so instead of copy paste the code between OnChange and OnLoad, you should use one of the following implementation styles:
1. Implementing the code in the OnChange event handler and using FireOnChange to execute it in the OnLoad event:
OnLoad
crmForm.all.my_lookup_field.FireOnChange();
OnChange
if (crmForm.all.my_lookup_field.DataValue != null) {
crmForm.all.my_text_field.DataValue = crmForm.all.my_lookup_field.DataValue[0].name;
}

else {
crmForm.all.my_text_field.DataValue = null;
}
2. Implementing the code in OnLoad and calling it from the OnChange event:
OnLoad
MyLookup_OnChange = function() {
if (crmForm.all.my_lookup_field.DataValue != null) {
crmForm.all.my_text_field.DataValue = crmForm.all.my_lookup_field.DataValue[0].name;
}

else {
crmForm.all.my_text_field.DataValue = null;
}
}

MyLookup_OnChange();
OnChange
MyLookup_OnChange();
The second implementation has the benefit that all of your code is in a single place.
Tip: The code can be rewritten to this:


var lookupValue = crmForm.all.my_lookup_field.DataValue;
crmForm.all.my_text_field.DataValue = (lookupValue == null) ? null : lookupValue[0].name;
Getting notified when the user selected an address in the address picker (quote, order, invoice)
When working with quotes, orders and invoices, you pick an address to specify the bill to and ship to address. Though the address fields are properly filled with the selected values, no OnChange event is executed in the CRM form. Here's an easy but unsupported way to be informed when the user closes the address lookup dialog:
if (document.all._MBLookupAddress != null) {
document.all._MBLookupAddress.onclick = function() {
LookupAddress();
alert("Address lookup closed");
}
}
You don't know if the user selected an address or canceled the operation though. You can use the same idea to override other built-in functions, but as said, it's unsupported and may break in future releases.
What is "if (condition) ? statement1 : statement2"?
I'm using the above notation a lot because it's an easy way to set a value to one out of two values. This construct is available in C, C++, Java, C# and I'm sure that most other languages have similar commands. I noticed though that it's not as as clear as I thought, so here's the same using a standard if/then/else:
if (condition) {
statement1;
}

else {
statement2;
}
And here's a real example:
var s = (crmForm.all.my_lookup.DataValue == null) ? null : crmForm.all.my_lookup.DataValue[0].name;
And the same with an if/then/else:
var s;

if (crmForm.all.my_lookup.DataValue == null) {
s = null;
}

else {
s = crmForm.all.my_lookup.DataValue[0].name;
}


Copying the display name of a selcted lookup value into a textbox
See the sample above.


Retrieving all fields inside a CRM form
If you want to loop over all fields (input fields) on a CRM form, you can use the following script as a starting point:
for (var index in crmForm.all) {
var control = crmForm.all[index];

if (control.req && (control.Disabled != null)) {
//control is a CRM form field
}
}
The conditions mean that a control must have the "req" attribute and the "Disabled" method. This seems a good indicator for a CRM form field.
Knowing if you are running in CRM 3.0 or CRM 4.0
It's fairly easy to differentiate if your code is running on CRM 4.0 or not. Just pick a method or variable that did not exist in CRM 3.0 and check if it is available:
if (typeof(GenerateAuthenticationHeader) == "undefined") {
alert("Version 3");
}

else {
alert("Version 4");
}
GenerateAuthenticationHeader was introduced in CRM 4.0 and is a global function available in all forms.



Showing/Hiding tabs based on the selection in a picklist
The next script shows one out of three tabs based on the selection in the new_combo field. It hides all tabs if no selection is made or a different value is selected.
OnLoad:
//Sanity check: if new_combo is not present on the form, then don't call FireOnChange
if (crmForm.all.new_combo != null) {
crmForm.all.new_combo.FireOnChange();
}
OnChange:
//Check for create, update, read-only or disabled form
if ((crmForm.FormType >= 1) && (crmForm.FormType
__________________
Расскажите о новых и интересных блогах по Microsoft Dynamics, напишите личное сообщение администратору.
 

Похожие темы
Тема Автор Раздел Ответов Посл. сообщение
CRM DE LA CREME! CRM 4.0 Disaster Recovery Blog bot Dynamics CRM: Blogs 2 26.02.2016 08:23
CRM DE LA CREME! Update Rollup 9 for Microsoft Dynamics CRM 4.0 Blog bot Dynamics CRM: Blogs 0 12.02.2010 16:05
CRM DE LA CREME! Hides the associated Views buttons/More Actions menu drop down Blog bot Dynamics CRM: Blogs 0 10.02.2010 13:05
CRM DE LA CREME! Microsoft CRM 4.0 Update Rollup Best Practices Blog bot Dynamics CRM: Blogs 0 18.08.2009 11:05
CRM DE LA CREME! Configuring Microsoft Dynamics CRM 4.0 for Internet-facing deployment Blog bot Dynamics CRM: Blogs 0 18.08.2009 11:05

Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.
Быстрый переход

Рейтинг@Mail.ru
Часовой пояс GMT +3, время: 09:40.
Powered by vBulletin® v3.8.5. Перевод: zCarot
Контактная информация, Реклама.