Wednesday, 3 February 2021

How to prevent record from saving in Dynamics CRM using Javascript

 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 usefil.

Happy Code! J


No comments:

Post a Comment

𝗣𝗼𝘄𝗲𝗿 𝗣𝗹𝗮𝘁𝗳𝗼𝗿𝗺 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀 – 𝗕𝗲𝗴𝗶𝗻𝗻𝗲𝗿 𝘁𝗼 𝗘𝘅𝗽𝗲𝗿𝘁

  🔰 𝗣𝗼𝘄𝗲𝗿 𝗣𝗹𝗮𝘁𝗳𝗼𝗿𝗺 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀 – 𝗕𝗲𝗴𝗶𝗻𝗻𝗲𝗿 𝘁𝗼 𝗘𝘅𝗽𝗲𝗿𝘁 🚀 🟢 𝗕𝗲𝗴𝗶𝗻𝗻𝗲𝗿 / 𝗝𝘂𝗻...