Dynamics CRM 2011 JavaScript Get Attribute from OnChange

Paul Nieuwelaar, 10 June 2012

When writing JavaScript for Dynamics CRM 2011, we often write functions that can be used multiple times, across different fields and entities. Because the field names are usually different, these variable names are often passed in as a parameter. This means each time we use the function we need to type in the field name, even if it is the same fields OnChange that we are calling the function from!

 Dynamics CRM 2011 JavaScript Get Attribute from OnChange

If we are going to be using the same function across multiple fields, we can simply get the fields attribute and/or name from the context, so we don’t need to enter the field name each time we call the function from an OnChange event.

NOTE: The attribute can only be retrieved from an OnChange event, and not an OnLoad event.

The attribute is retrieved from the execution context of the function. So this means when adding the event handler, you need to tick the box to ‘Pass execution context as first parameter’. You do not need to enter the field name into the parameters.

 Dynamics CRM 2011 JavaScript Get Attribute from OnChange

In your JavaScript function now, you need to add ‘executionContext’ as the first parameter. You can then use the following code to get the fields attribute from the context:

function formatPhoneNumber(executionContext) {
    var attribute = executionContext.getEventSource();
}

We can then proceed to perform normal actions against the attribute as if we had gotten it using Xrm.Page, for example the following code will get the schema name of the field from the attribute, which can then be used to retrieve the fields control if necessary:

    var fieldName = attribute.getName(); //the field schema name
    var control = Xrm.Page.getControl(fieldName); //the control 

When used multiple times, this saves a lot of time not having to worry about finding the field schema name before adding the event. It also eliminates the possibility of entering the field name incorrectly.