Search code examples
javascriptformsevent-handlingdynamics-crmmicrosoft-dynamics

How can I prevent a form from saving in Dynamics 365


I want to prevent a form from saving if the entered "dni" value is already registered by another "person", I tried to keep the form from saving in its onSave event, and then if my condition matched, I'd make the form save then. So I made the following code:

function saveDni(executionContext) {
  try {
    const formContext = executionContext.getFormContext();
    const currentDni = formContext.getAttribute("cr6ff_dni").getValue();
    
    executionContext.getEventArgs().preventDefault();

    var fetchXml = [
      "<fetch top='1'>",
      "  <entity name= 'cr6ff_person'>",
      "    <filter>",
      "      <condition attribute='cr6ff_dni' operator='eq' value='", currentDni, "'/>",
      "    </filter>",
      "  </entity>",
      "</fetch>",
    ].join("");

    fetchXml = "?fetchXml=" + encodeURIComponent(fetchXml);

    Xrm.WebApi.retrieveMultipleRecords("cr6ff_person", fetchXml).then(
      (result) => {
        if (result.entities.length == 0) {
          formContext.data.entity.save();
        }
     }
   ) 
}
catch(error) {
  console.log("An error has occurred while validating the user's data.");
}

The thing is, when the save() method triggers, it also triggers this function back again, so I'm stuck in a loop. Any ideas as to how I could work this out?


Solution

  • Let me recommend you the best practices.

    1. Avoid Asynchronous calls like Xrm.WebApi.retrieveMultipleRecords in form save for better User experience. Read more
    2. formContext.data.entity.save() is deprecated, use formContext.data.save() instead. Reference
    3. Better to move the business logic validation to server side plugin or Power automate flow