Sean Sean - 1 month ago 15
Javascript Question

Dynamics Crm 2016 online: client-side record creation preventing not working

I try to prevent the creation of an appointment if some conditions are satisfied, but the line

Xrm.Page.context.getEventArgs().preventDefault();
does not work and the record is created. Here is the entire code, the call is synchronous:

var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.0/appointments?$select=activityid&$filter=<my filter>", false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"OData.Community.Display.V1.FormattedValue\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
if(results.value.length > 0)
{
Xrm.Utility.alertDialog('It is impossible to create the appointment.');
Xrm.Page.context.getEventArgs().preventDefault();
}
}
else {
alert(this.statusText);
}
}
};
req.send();

Answer

Your code should be erroring out at Xrm.Page.context.getEventArgs(), there is no property on the page's context object for event argument.

You should pass the execution context on save and then use the execution context's event arguments to stop the save.

Form Customization:

enter image description here

Handler:

function onSave(executionContext) {
  if(results.value.length > 0)
  {
    Xrm.Utility.alertDialog('It is impossible to create the appointment.');
    executionContext.getEventArgs().preventDefault();
  }
}
Comments