A CRM Validation Rule that prevents users from changing a Sales Order's status to 'Closed' unless there is at least one Invoice related to it.
Often, sales reps will mark a Sales Order as "Closed" or "Delivered" without actually generating an invoice for the accounting team. This creates massive discrepancies in reporting and delays revenue collection. We need a hard stop in the UI that prevents a record from saving if it violates this business rule.
Using Zoho CRM's Validation Rules (specifically, Custom Functions for Validation), we can write a Deluge script that intercepts the save action.
The script checks if the user is attempting to change the status to "Closed". If they are, it queries the related "Invoices" list. If the list is empty, it returns a hard error directly to the CRM UI, blocking the save.
Unlike standard workflows that trigger after a save, Validation Rules trigger during the save. Because the record hasn't been committed to the database yet, we cannot use standard zoho.crm.getRecordById. Instead, we parse the incoming crmAPIRequest map to view the exact data the user is trying to submit.
Navigate to Settings > Modules and Fields > Sales Orders > Validation Rules. Choose the "Status" field. In the rule criteria, choose to execute a custom function, and paste this code.
// Extract Sales Order ID and Status from the CRM API Request
entityMap = crmAPIRequest.toMap().get("record");
saleorderid = entityMap.get("id");
status = entityMap.get("Status");
response = Map();
// Fetch related Invoices for this Sales Order
invoices = zoho.crm.getRelatedRecords("Invoices", "Sales_Orders", saleorderid);
// Validation: Prevent closing the Sales Order if no Invoices exist
// Note: 'סגור' means 'Closed'
if(invoices.isNull() && status == "סגור")
{
response.put("status", "error");
response.put("message", "לא ניתן לסגור הזמנה ללא חשבונית קשורה"); // "Cannot close order without related invoice"
}
else
{
response.put("status", "success");
}
return response;