OnChange Events on a Dynamics CRM 4.0 Picklist

Paul Nieuwelaar, 14 July 2010

In an earlier post by Nathan, titled Hiding Fields Based on User Selection, he went through hiding a field when a user selects ‘yes’ or ‘no’ from a bit attribute. However, when I came to do this, when a user picks an option from a picklist (dropdown) attribute, the method was quite different.

For this example I will use the default ‘Relationship Type’ picklist on the Account form. So that if ‘Other’ is selected, a field labelled Specify will appear below the ‘Relationship Type’ picklist.

To do this, you must first create the text field attribute and place it on the form below ‘Relationship Type’. I also made the text field Business Required, so that they have to specify the other relationship type.

The next thing you want to do is open up the ‘Relationship Type’ attribute, which is called customertypecode. Select the item you will be using, in this case it is ‘Other’. Click edit, and note down the value (for 'Other' the value is 12). Open up the form again, select the ‘Relationship Type’ attribute, and click Change Properties. On the Events tab click Edit ‘onChange’. Make sure you check Event is enabled, and then add the following code:

// If the selected value is Other, display Specify, and set requirement to Business Required

if (crmForm.all.customertypecode.DataValue == "12") {

crmForm.all.new_specify_c.style.display = "";

crmForm.all.new_specify_d.style.display = "";

crmForm.SetFieldReqLevel("new_specify", 1);

}

// If the selected value is not Other, hide Specify, and set requirement to Not Required

else {

crmForm.all.new_specify_c.style.display = "none";

crmForm.all.new_specify_d.style.display = "none";

crmForm.SetFieldReqLevel("new_specify", 0);

}

 

Change where it has ‘customertypecode’ to be the name of the picklist, and change ‘new_specify’ to be the name of the Specify text box that is being displayed. If the value of ‘Other’ is not 12, change it to the correct value.

NOTE: For values that have commas, ‘200,000’ for example, you must make sure you do not include the comma in the code, so it would just be written as ‘200000’.

You will also need to add all this code to the forms ‘onLoad’ event, but instead of copy pasting it straight in, a better practice is to add the following line:

crmForm.all.customertypecode.FireOnChange();

Where ‘customertypecode’ is the name of the picklist. What this will do is run the ‘onChange’ event for ‘customertypecode’ when the form loads. So if you ever needed to change the code in the picklist ‘onChange’, you would not need to update the ‘onLoad’ as well.