Cancel the save based on the result of an asynchronous operation

In 2017, Natraj Yegnaraman shared a clever method to cancel the save of a form. His approach was to cancel the save before the asynchronous operation and then retrigger the save if needed after the asynchronous operation is resolved. You can find all the details on the following link.

This approach is explained by the fact that the save handler was always synchronous. Now in 2021, Microsoft has given the possibility to switch the save handler from synchronous mode to asynchronous mode. The process to enable the asynchronous mode for the save handler is explained in Microsoft Docs.

Below, I am sharing an example to cancel the save using the new method preventDefaultOnError() proposed by the client api. Please note, you must first activate the asynchronous mode on your MDA before starting.


Scenario 1:

if (typeof (MEA) == "undefined") { MEA = {} };
if (typeof (MEA.Account) == "undefined") { MEA.Account = {} };
if (typeof (MEA.Account.AccountForm) == "undefined") { MEA.Account.AccountForm = {} };
MEA.Account.AccountForm = {
onLoad: function (executionContext) {
var formContext = executionContext.getFormContext();
formContext.data.entity.addOnSave(
(() => {
var asyncSaveValidation = (saveCtx) => {
return new Promise((resolve, reject) => {
//timeout 10 sec
//reject("error");
});
};
return async (saveCtx) => {
saveCtx.getEventArgs().preventDefaultOnError();
let result = await asyncSaveValidation(saveCtx);
}
}
)());
}
}
view raw AccountForm.js hosted with ❤ by GitHub

The save is blocked and the following error is displayed


Scenario 2:

if (typeof (MEA) == "undefined") { MEA = {} };
if (typeof (MEA.Account) == "undefined") { MEA.Account = {} };
if (typeof (MEA.Account.AccountForm) == "undefined") { MEA.Account.AccountForm = {} };
MEA.Account.AccountForm = {
onLoad: function (executionContext) {
var formContext = executionContext.getFormContext();
formContext.data.entity.addOnSave(
(() => {
var asyncSaveValidation = (saveCtx) => {
return new Promise((resolve, reject) => {
saveCtx.getEventArgs().preventDefault();
reject("error");
});
};
return async (saveCtx) => {
try {
await asyncSaveValidation(saveCtx);
}
catch (error) {
console.log(error);
}
}
}
)());
}
}
view raw AccountForm.js hosted with ❤ by GitHub

In this case, the save is canceled, and no error is displayed.

One thought on “Cancel the save based on the result of an asynchronous operation

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s