CRM 2011 - JavaScript Events

For the experienced developers, you might be quick to bind to HTML objects to handle events.  Stop!  Read my blog!  And roll!

For those of you just picking up JavaScript, an Event is a way to “trigger” code to execute when something happens.  For example, if a user selects something in a drop down you can use an “OnChange” event to show an otherwise hidden section.  Events are a great way to enhance the user experience as well as to improve the quality of data input.  Today we’re going to look at the events supplied by CRM 2011 and how to use those in a coherent way without having to bind to an event in a crazily unsupported fashion.

 


CRM 2011 Events

To attach (aka bind or listen) to an event (100% supported), you’ll need to have a JavaScript web resource with a function you want to execute.  Inside of the form editor, you’ll want to click “Form Properties” and then make sure you’re on the Events tab.  From here, you can select the control and the appropriate event.  Here’s an example of the Event Handler section of the form:

image

 

CRM 2011 provides a bevy of events:

  • Form Events
    • OnLoad – This is for code to execute once the form has finished loading.  When you customize CRM 2011 forms with JavaScript, this is your bread & butter.  Whether it’s showing/hiding fields, toggling fields to read-only, or alerting the user that an account is on credit hold; the OnLoad event is what you want the form to do immediately after the user opens the form.
    • OnSave – Frequently used to validate data on the form, this event allows you to ensure the user entered the appropriate information.  (Note: if it’s mission critical, then use a plug-in.)
  • Field Events
    • OnChange – This fires after the user leaves a field they just changed.  Typically this is used to format or validate a field.
      Note: It is important to know the difference between OnChange and the unsupported OnBlur.
  • iFrame Events
    • OnReadyStateChange – This is similar to the OnLoad event for the Form, but fires when the iFrame has finished loading.  A nice example of this is when you want to execute something inside of the iFrame based on a field selection in you form.
    • In addition to the OnReadyStateChange, don’t forget that you can pass parameters to the iFrame.  The page inside the iFrame, will need to read the URL parameters and process them appropriately, but this is somewhat event related since you can process the URL server side or client side once the page is loaded (from within the iFrame).
  • Tab Events
    • TabStateChanged – This event fires when the tab is Expanded or Collapsed.  Most of the time, you won’t need this event; however, it comes in handy when refreshing iFrames.

 

What’s Missing?

A lot.  But honestly CRM supplies everything you need.

There is a gotcha though that I think developers, users, and customizers should be aware of: the OnBlur vs OnChange.

OnBlur is not an option for you to choose from inside CRM 2011.  If you take a look at an email field however, you’ll see a great example of an OnBlur.  Try entering “paul” inside an email field and you’ll be prompted with this warning:

image

Notice that you can’t tab off of the field without entering a valid email address (or completely blanking out the field).  The reason for this is because the OnBlur fires every time the user leaves the field.

OnChange on the other hand only fires when the field changed and NOT when the user leaves the field.  An example is like so:

function example(obj){
alert(obj.getEventSource().getValue());
}

image

Make sure to pass execution context in this example.

 

Here the user will be presented with the prompt of whatever their value was.  Which seems fine, until we go back to the field and tab off.  Notice that it doesn’t fire again.

Real World Example

Let’s say I want to validate the mobile phone number field to be a particular format (3 – 3 – 4 digits to be exact).  To do this, I could change the function above to:

function example(obj){
var rgCell = /[0-9]{3}-[0-9]{3}-[0-9]{4}/;
var sVal = obj.getEventSource().getValue();

    if (rgCell.test(sVal)) {
// valid

    } else {
// Invalid phone number
alert('Please enter a valid phone number (ex. 123-123-1234).');
}
}

 

With the above code, the user will be alerted but then is able to save the form with data that doesn’t match our desired format.

 

How do I Validate with OnChange?

Luckily this isn’t really that big of a deal.  There are several options and its really whatever is best for you.

Option 1: Blank the field.

By far the easiest option is to just clear the field after prompting the user.  The only downside is the user has to re-enter all of the data again.

function example(obj){
var rgCell = /[0-9]{3}-[0-9]{3}-[0-9]{4}/;
var sVal = obj.getEventSource().getValue();

    if (rgCell.test(sVal)) {
// valid

    } else {
// Invalid phone number
alert('Please enter a valid phone number (ex. 123-123-1234).');
obj.getEventSource().setValue('');
}

}

 

Option 2: Utilize the OnSave

There is a little more effort involved here, but a better experience for the user.

function example(obj){
var rgCell = /[0-9]{3}-[0-9]{3}-[0-9]{4}/;
var sVal = Xrm.Page.getAttribute("mobilephone").getValue();  //obj.getEventSource().getValue();

    if (rgCell.test(sVal)) {
// valid
} else {
// Invalid phone number
alert('Please enter a valid phone number (ex. 123-123-1234).');
Xrm.Page.getAttribute("mobilephone").controls.get(0).setFocus();  // only fires onSave

if (obj.getEventArgs() != null)
obj.getEventArgs().preventDefault();
}
}

To add to the OnSave, we’ll need to register the event inside the Form Properties (as well as pass execution context).

image

 

Here the user will be alerted when they first enter an invalid formatted phone number.  At the point of Saving the form, the user will be prompted until they enter a properly formatted phone number.

Taking it Further

By combing the OnSave with the OnChange, you can set the label or background to red, float div elements, or inject an error message underneath the field.   There are plenty of options for styling the form to further enhance the user experience if so desired.

 

What about the OnBlur?

The OnBlur option is currently unsupported.  Although certainly something you could do, as you can see the email field is already doing this, there are some pitfalls (like the infinite loop of alert boxes).  I’d avoid dynamically binding to the OnBlur for several reasons, but mainly because if an updates breaks your code now the validation is completely broken.

As a side note, with multiple browsers coming down the pipeline for CRM 2011, it’s important to realize attachEvent is Internet Explorer specific. For other browsers, you’ll need to use addEventListener. Although this isn’t a huge deal, it is yet another reason to stay with supported code and to use the built in event handlers.

 

Conclusion

The event handlers provided within CRM 2011 encompass the full gamut of users needs.  Sometimes you’ll have to combine multiple events to get the exact functionality you’re looking for, but the events are well thought out and are intended to be used in conjunction with one another.

I hope you enjoy!

Post by: Paul Way, Customer Effective

Show Buttons
Hide Buttons