I have 2 functions -
1. checkTemplate
2. onSaveBlockSaveIfNotOfficial
Using a Global flag variable
The checkTemplate is being called on the OnChange event of the Template in Dynamics 365 where it retrieves the Template ID, Template Name based on the Template selected.
The onSaveBlockSaveIfNotOfficial is the function called on the OnSave event of the form and if the Template name has the word "Official" in it then it returns the result, and the user is able to save their email.
If the Template does not have the word 'Official' then it shows an alert which is Xrm.Navigation.openAlertDialog. and it keeps popping up in a loop.
Below is my code
//global flag variable
var templateHasOfficial = false;
//call on change of Template
function checkTemplate(executionContext) {
var formContext = executionContext.getFormContext();
var templateId = formContext.getAttribute("msdynmkt_templateid").getValue()[0].id;
var templateIdNew = templateId.replace("{", "").replace("}", "");
//Check if the ID or value exists
if (!templateIdNew) return;
try {
const result = Xrm.WebApi.retrieveRecord("msdynmkt_emailtemplate", templateIdNew, "?$select=msdynmkt_name");
templateHasOfficial = result.msdynmkt_name && result.msdynmkt_name.toUpperCase().includes("Official");
} catch (error) {
console.error("Error retrieving template:", error.message);
templateHasOfficial = false;
};
}
//call OnSave of the form
function onSaveBlockSaveIfNotOfficial(executionContext) {
var eventArgs = executionContext.getEventArgs();
if (!templateHasOfficial) {
eventArgs.preventDefault();
Xrm.Navigation.openAlertDialog({
text: "Please select a valid Official Email Template.",
title: "Invalid Template",
confirmButtonLabel: "OK"
});
}
}