To restrict users from creating activities (meeting, chat, email, phone call) when the related contact is inactive, you can modify the provided JavaScript as follows:
Check if the form is in "Create" mode.
Retrieve the related contact (regardingobjectid).
Fetch the contact's state (active/inactive) using Xrm.WebApi.retrieveRecord
.
If the contact is inactive (statecode = 1), show a warning and prevent further processing.
If the contact has an associated account, update the regarding object to that account.
Handle Chat activity separately, ensuring the contact is added to the "To" field.
Code Update:
Ensure the function is async
.
Use try-catch
for error handling around the API call.
Implement an early return to stop further activity creation when the contact is inactive.
Try this code :
async function updateRegardingInActivities(executionContext) {
const formContext = executionContext.getFormContext();
formContext.ui.clearFormNotification("notification");
// Get the regarding object (the related contact)
const regarding = formContext.getAttribute("regardingobjectid").getValue();
// If the form is in Create mode (Form Type 1)
if (formContext.ui.getFormType() === 1 && regarding !== null) {
// Check if the regarding object is a contact
if (regarding[0].entityType === "contact") {
// Retrieve the related contact's status (statecode) from the system
try {
const contactDetails = await Xrm.WebApi.retrieveRecord("contact", regarding[0].id, "?$select=fullname,statecode&$expand=parentcustomerid_account($select=name,accountid)");
// If the contact is inactive (statecode == 1)
if (contactDetails.statecode === 1) {
formContext.ui.setFormNotification("Related contact is inactive, you cannot create activity.", "WARNING", "notification");
return; // Prevent further processing if the contact is inactive
}
// If the contact has a related account, update the regardingobjectid to the account
if (contactDetails.parentcustomerid_account !== null) {
const accountLookup = [{
id: contactDetails.parentcustomerid_account.accountid,
name: contactDetails.parentcustomerid_account.name,
entityType: "account"
}];
formContext.getAttribute("regardingobjectid").setValue(accountLookup);
}
// Handle Chat activity: Add related contact to 'To' field
if (formContext.ui.formSelector.getCurrentItem().getLabel() === "Chat") {
const contactLookup = [{
id: regarding[0].id,
name: contactDetails.fullname,
entityType: "contact"
}];
formContext.getAttribute("to").setValue(contactLookup);
}
} catch (error) {
console.error("Error retrieving contact details: ", error);
formContext.ui.setFormNotification("Error fetching contact details, please try again later.", "ERROR", "notification");
}
}
}
}
This approach should prevent activity creation for inactive contacts and update the UI accordingly.