POWEROBJECTS

718 Washington Ave. N. Suite #101
Minneapolis, MN 55401
View map and all Locations

Send us a message

We’ve covered some great ways to use JavaScript in Dynamics CRM 2011 in previous posts. This post focuses on a use that we recently employed for a client. In Microsoft Dynamics CRM 2011 or 4.0, you may want to use JavaScript in to set the value in read-only field on a form. However, you may have noticed that after the JavaScript sets the field to Read-Only, it does not save the value when the record is saved.

crm2011

To clarify, consider the following scenario.

On the Account form, your goal is to have the “Account Number” field become Read-Only if a checkbox is checked. In this example, we’ll name the checkbox “Freeze.” What you may do to accomplish this is to have the “Account Number” field become Read-Only onChange of the “Freeze” checkbox. You would also want this JavaScript to fire onLoad as well. This will accomplish what you’re attempting to do…almost.

Now, when you deploy this code (to a test system of course), you find something strange happens. Let’s say a user edits the “Account Number” field, then checks the “Freeze” box immediately after. Upon saving the record, the “Account Number” field reverts back to the previous value. Why is this? Well, prior to checking the “Freeze” field, the “Account Number” field was editable. If we edit that field on the form, the actual field in the database is not modified until we save the record. So, if we edit the field, check the “Freeze” box then Save the record, the value will not be changed because the “Account Number” field was set as Read-Only as soon as we check the box (from the onChange event) prior to saving the record.

To meet this requirement, you could use option #1 below, or use a combination of the two.

#1    Have the JavaScript code fire onLoad of the form ONLY. Not onChange of the “Freeze” field.

Here is the code for the onLoad event:

The downside of this method alone is that even though the user checks the box, the Account Number field is not yet Read-Only. To resolve this, add step #2 to the equation.

#2    In your onChange event for the “Freeze” field, instead of using the code above, simply utilize some code to “Save” the record. When a user checks the “Freeze” box, the record is saved and reloaded. The code in #1 will then fire onLoad, thus setting he “Account Number” field as Read-Only.

Here is the code for the onChange event:

Didn’t get your fill of JavaScript yet? Here are some more posts on how to use JavaScript in Dynamics CRM:

Happy CRM’ing!

Avatar for JoeCRM

JoeCRM

Joe CRM is a CRM superhero who runs on pure Microsoft Dynamics CRM adrenaline. As the face of PowerObjects, Joe CRM’s mission is to reveal innovative ways to use Dynamics CRM and bring the application to more businesses and organizations around the world.