Rules and Events

0
67
10 min read

(For more resources related to this topic, see here.)

Handling specifc events is something everybody expects from an application. While JavaScript has its own event handling model, working with Dynamics CRM offers a different set of events that we can take advantage of.

The JavaScript event model, while it might work, is not supported, and defnitely not the approach you want to take when working within the context of Dynamics CRM.

Some of the most notable events and their counterparts in JavaScript are described in the following table:

Dynamics CRM 2011

JavaScript

Description

OnLoad

onload

This is a form event. Executes when a form is loaded. Most common use is to filter and hide elements on the form.

OnSave

onsubmit

This is a form event. It executes when a form is saved. Most common use is to stop an operation from executing, as a result of a failed validation procedure.

TabStateChange

n/a

This is a form event. It executes when the DisplayState of the tab changes.

OnChange

onchange

This is a field specific event. It executes when tabbing out of a field where you’ve changed the value. Please note that there is no equivalent for onfocus and onblur.

OnReadyStateComplete

n/a

This event indicates that the content of an IFrame has completed loading.

Additional details on Dynamics CRM 2011 specifc events can be found on MSDN at http://msdn.microsoft.com/en-us/library/gg334481.aspx.

Form load event usage

In this recipe, we will focus on executing a few operations triggered by the form load event. We can check the value of a specifc field on the form, and based on that we can decide to hide a tab, hide a field, and prepopulate a text field with a predefned value.

Getting ready…

Just as with any of the previous recipes, you will need access to an environment, and permissions to make customizations. You should be a system administrator, a system customizer, or a custom role configured to allow you to perform the following operations.

How to do it…

For the purpose of this exercise, we will add to the Contact entity a new tab called “Special Customer”, with some additional custom fields. We will also add an option set that we will check to determine if we hide or not the fields, as well as two new fields: one text field and one lookup field. So let’s get started!

  1. Open the contact’s main form for editing.
  2. Add a new tab by going to Insert | Tab | One Column.
  3. Double-click on the newly added tab to open the Tab Properties window.
  4. Change the Label field of the tab to Special Customer.
  5. Make sure the show label is expanded by default and visible checkboxes are checked. Click on OK.
  6. Add a few additional text fields on this tab. We will be hiding the tab along with the content within the tab.
  7. Add a new field, named Is Special Customer (new_IsSpecialCustomer). Leave the default yes/no values.
  8. Add the newly created field to the general form for the contact.
  9. Add another new text field, named Customer Classifcation (new_ CustomerClassifcation). Leave the Format as Text, and the default Maximum Length to 100, as shown in the following screenshot:
  10. Add the newly created text field to the general form, under the previously added field.
  11. Add a new lookup field, called Partner (new_Partner). Make it a lookup for a contact, as shown in the following screenshot:
  12. Add this new field to the general form, under the other two fields.
  13. Save and Publish the Contact form.
  14. Your form should look similar to the following screenshot:
  15. Observe the fact that I have ordered the three fields one on top of the other. The reason for this is because the default tab order in CRM is vertical and across. This way, when all the fields are visible, I can tab right from one to another.

  16. In your solution where you made the previous changes, add a new web resource named FormLoader (new_FormLoader). Set the Type to JScript.
  17. Click on the Text Editor button and insert the following function:
  18. function IsSpecialCustomer()
    {
    var _isSpecialSelection = null;
    var _isSpecial = Xrm.Page.getAttribute("new_isspecialcustomer");
    if(_isSpecial != null)
    {
    _isSpecialSelection = _isSpecial.getValue();
    }
    if(_isSpecialSelection == false)
    {
    // hide the Special Customer tab
    Xrm.Page.ui.tabs.get("tab_5").setVisible(false);
    // hide the Customer Classification field
    Xrm.Page.ui.controls.get("new_customerclassification").
    setVisible(false);
    // hide the Partner field
    Xrm.Page.ui.controls.get("new_partner").setVisible(false);
    }
    }

  19. Save and Publish the web resource.
  20. Go back to the Contact form, and on the ribbon select Form Properties.
  21. On the Events tab, add the library created as web resource in the Forms Libraries section, and in the Event Handlers area, on the Form OnLoad add the function we created:
  22. Click on the Text Editor button and insert the following function:
  23. Click on OK, then click on Save andPublish the form
  24. Test your configuration by opening a new contact, setting the Is Special Customer field to No. Save and close the contact. Open it again, and the tab and fields should be hidden.

How it works…

The whole idea of this script is not much different from what we have demonstrated in some of the previous recipes. Based on a set form value, we hide a tab and some fields. Where we capture the difference is where we set the script to execute. Working with scripts executing when the form loads gives us a whole new way of handling various scenarios.

There’s more…

In many scenarios, working with the form load events in conjunction with the other field events can potentially result in a very complex solution.

When debugging, always pay close attention to the type of event you associate your script function with.

See also

See the Combining events recipe towards the end of this article for a more complex recipe detailing how to work with multiple events to achieve the expected result.

Form save event usage

While working with the Form OnLoad event can help us format and arrange the user interface, working with the Form OnSave opens up a new door towards validation of user input and execution of business process amongst others.

Getting ready

Using the same solution we have worked on in the previous recipe, we will continue to demonstrate a few other aspects of working with the forms in Dynamics CRM 2011. In this recipe the focus is on the handling the Form OnSave event.

How to do it…

First off, in order to kick off this, we might want to verify a set of fields for a condition, or perform a calculation based on a formula. In order to simplify this process, we can just check a simple yes/no condition on a form.

How it works…

Using the previously customized solution, we will be taking advantage of the Contact entity and the fields that we have already customized on that form. If you are starting with this recipe fresh, take the following step before delving into this recipe:

  1. Add a new two-options field, named Is Special Customer (new_IsSpecialCustomer). Leave the default yes/no values.
  2. Using this field, if the answer is No, we will stop the save process.

  3. In your solution add a new web resource. I have named it new_ch4rcp2. Set its type to JScript.
  4. Enter the following function in your resource:
  5. function StopSave(context)
    {
    var _isSpecialSelection = null;
    var _isSpecial = Xrm.Page.getAttribute("new_isspecialcustomer");
    if(_isSpecial != null)
    {
    _isSpecialSelection = _isSpecial.getValue();
    }
    if(_isSpecialSelection == false)
    {
    alert("You cannot save your record while the Customer is not a
    friend!");
    context.getEventArgs().preventDefault();
    }
    }

  6. The function basically checks for the value in our Is Special Customer. If a value is retrieved, and that value is No, we can bring up an alert and stop the Save and Close event.
  7. Now, back on to the contact’s main form, we attach this new function to the form’s OnSave event.
  8. Save and Publish your solution.
  9. In order to test this functionality, we will create a new contact, populate all the required fields, and set the Is Special Customer field to No.
  10. Now try to click on Save and Close.
  11. You will get an alert as seen in the following screenshot, and the form will not close nor be saved.
  12. Changing the Is Special Customer selection to Yes and saving the form will now save and close the form.

There’s more…

While this recipe only describes in a very simplistic manner the way to stop a form from saving and closing, the possibilities here are immense. Think about what you can do on form save, and what you can achieve if a condition should be met in order to allow the form to be saved.

Starting a process instead of saving the form

Another good use for blocking the save and close form is to take a different path. Let’s say we want to kick off a workfow when we block the save form. We can call from the previous function a new function as follows:

function launchWorkflow(dialogID, typeName, recordId)
{
var serverUri = Mscrm.CrmUri.create('/cs/dialog/rundialog.aspx');
window.showModalDialog(serverUri + '?DialogId=' + dialogID +
'&EntityName=' + typeName +
'&ObjectId=' + recordId, null, 'width=615,height=480,resizable=1,statu
s=1,scrollbars=1');
// Reload form
window.location.reload(true);
}

We pass to this function the following three parameters:

  • GUID of the Workfow or Dialog
  • The type name of the entity
  • The ID of the record

See also

For more details on parameters see the following article on MSDN:

http://msdn.microsoft.com/en-us/library/gg309332.aspx

Field change event usage

In this recipe we will drill down to a lower level. We have handled form events, and now it is time to handle field events. The following recipe will show you how to bring all these together and achieve exactly the result you need.

Getting ready

For the purpose of this recipe, let’s focus on reusing the previous solution. We will check the value of a field, and act upon it.

How to do it…

In order to walkthrough this recipe, follow these steps:>

  1. Create a new form field called new_changeevent, with a label of Change Event, and a Type of Two Options. Leave the default values of No and Yes. Leave the Default Value as No.
  2. Add this field to your main Contact form.
  3. Add the following script to a new JScript web resource:

    function ChangeEvent()
    {
    var _changeEventSelection = null;
    var _isChanged = Xrm.Page.getAttribute("new_changeevent");
    if(_isChanged != null)
    {
    _changeEventSelection = _isChanged.getValue();
    }
    if(_changeEventSelection == true)
    {
    alert("Change event is set to True");
    // perform other actions here
    }
    else
    {
    alert("Change event is set to False");
    }
    }

  4. This function, as seen in the previous recipes, checks the value of the Two Options field, and performs and action based on the user selection. The action in this example is simply bringing an alert message up.
  5. Add the new web resource to the form libraries.
  6. Associate this new function to the OnChange event of the field we have just created.
  7. Save and Publish your solution.
  8. Create a new contact, and try changing the Change Event value from No to Yes and back. Every time the selection is changed, a different message comes up in the alert.

How it works…

Handling events at the field level, specifcally the OnSave event, allows us to dynamically execute various other functions. We can easily take advantage of this functionality to modify the form displayed to a user dynamically, based on a selection. Based on a field value, we can defne areas or field on the form to be hidden and shown.

LEAVE A REPLY

Please enter your comment!
Please enter your name here