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?
Let me recommend you the best practices.