Skip to content

Instantly share code, notes, and snippets.

@melamriD365
Created January 9, 2022 13:40
Show Gist options
  • Save melamriD365/0904d52f4dd62639c3fe4f21513024c0 to your computer and use it in GitHub Desktop.
Save melamriD365/0904d52f4dd62639c3fe4f21513024c0 to your computer and use it in GitHub Desktop.
Optimistic Concurrency in Model-Driven Apps Forms.
//Optimistic Concurrency in Model-Driven Apps Forms
var MEA = window.MEA || {};
var OptimisticConcurrencyForm = MEA.OptimisticConcurrencyForm || {};
(function () {
var versionNumber = null;
var entityReference = null;
this.OnLoad = async function (executionContext) {
var eventArgs = executionContext.getEventArgs();
if (eventArgs.getDataLoadState() == 1) {
var formContext = executionContext.getFormContext();
formContext.ui.addOnLoad(this.getVersionNumberOnLoad);
formContext.data.entity.addOnSave(this.validateOnSave);
formContext.data.entity.addOnPostSave(this.updateVersionNumberOnPostSave);
}
};
this.getVersionNumberOnLoad = async function (loadCtx) {
var formContext = loadCtx.getFormContext();
if (formContext.ui.getFormType() == 2) {
entityReference = formContext.data.entity.getEntityReference();
var onLoadResult = await Xrm.WebApi.retrieveRecord(entityReference.entityType, entityReference.id, "?$select=versionnumber");
versionNumber = onLoadResult["versionnumber"];
}
};
this.validateOnSave = async function (saveCtx) {
var validateRowVersion = (saveCtx, entityReference, versionNumber) => {
return (async () => {
var result = await Xrm.WebApi.retrieveRecord(entityReference.entityType, entityReference.id, "?$select=versionnumber");
var versionNumberFromServer = result["versionnumber"];
if (versionNumberFromServer == versionNumber) {
return true;
}
else {
saveCtx.getEventArgs().preventDefault();
return false;
}
})();
};
var formContext = saveCtx.getFormContext();
if (formContext.ui.getFormType() == 2) {
try {
var validationResult = await validateRowVersion(saveCtx, entityReference, versionNumber);
if (!validationResult) {
var errorOptions = { message: 'This record is already updated by another user! ' };
Xrm.Navigation.openErrorDialog(errorOptions);
}
}
catch (error) {
console.log(error);
}
}
};
this.updateVersionNumberOnPostSave = async function (postSaveCtx) {
if (postSaveCtx.getEventArgs().getIsSaveSuccess()) {
entityReference = postSaveCtx.getEventArgs().getEntityReference();
result = await Xrm.WebApi.retrieveRecord(entityReference.entityType, entityReference.id, "?$select=versionnumber");
versionNumber = result["versionnumber"];
}
}
}).call(OptimisticConcurrencyForm);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment