Tip #72: Granular notifications for end users

Today’s tip was supposed to be called “Why it’s very important to keep your SDK up to date” but instead I named it after the updated functionality that was added to CRM Online, released for onpremises in UR1 and documented in the December update of the SDK.

Previously, if you wanted to notify user about something, all you had was control.setNotification(message) and control.clearNotification() pair of functions, meaning that you probably would have cramped all your validations in one place.

Now, the functions have become control.setNotification(message, id) and control.clearNotification(id) and you have a slightly more granular control which notifications to add or dismiss. Disappointingly, if you add multiple notifications for the same control, only the last one is visible to the end-user but a) that may change and, regardless, b) code becomes easier to manage, especially when multiple rules and controls are involved.

Granular validation of multiple fields

Say, if I want to ensure the length of the name for the account and also validate that both account and phone number are alphanumeric then I might use the following code:

var validations = [];

function onLoad() {

  validations.push( {
    id: "tooshort",
    rule: function(v) {
      return !v || v.length < 3;
    },
    message: "Shorter than 3 chars"});

  validations.push( {
    id: "noa1",
    rule: function(v) {
      return /[^\w]/.test(v);
    },
    message: "Not alphanumeric"});

}

function validate(controlName, ruleId) {

  var ctrl = Xrm.Page.getControl(controlName);
  var value = ctrl.getAttribute().getValue();

  for(i=0;i<validations.length;i++) {
    var valObj = validations[i];
    if(valObj.id == ruleId) {
      if(valObj.rule(value))
        ctrl.setNotification(valObj.message, valObj.id);
      else
        ctrl.clearNotification(valObj.id);
    }
  }

}

Add declarative validation

and then bind onchange event for name fields to validate with parameters “name”, “tooshort”, then another bind with “name”, “noa1” and finally one for phone field with parameters “telephone1”, “noa1”, using a [somewhat] declarative validation. You did know you can bind more than one function to the same handler, didn’t you?

Note that setting a notification on a control will block the form from saving until all notifications are cleared.

Leave a Reply

Your email address will not be published. Required fields are marked *