Search This Blog

Tuesday, December 6, 2022

Javascript – Prevent Save

From time to time you might need to add some validation to the save event of an entity, this actually used to be an approach I would use on a regular basis but since the introduction of business rules have found myself doing this less and less. But still, knowing the ability is available is handy.

When you define the onsave event function, you must tick the “Pass execution contact as first parameter” option. (See below)

Having done that you can create an onSave function with code similar to the example I have shown below. Note forgetting the “(context)”, which will take the context parameter allowing you to prevent the save when needed.

function onSave(context) {
  var saveEvent = context.getEventArgs();
  if (Xrm.Page.getAttribute("telephone1").getValue() == null) {
    // *** Note: I am using an alert for testing a notification maybe better!
    alert("Put in a phone number!");
    saveEvent.preventDefault();
  }
}

Note: This simple example might be better achieved with a business rule but when you need complex validation that can’t be implemented with a business rule this approach is useful.


No comments:

Post a Comment