This article walks you through creating a validation rule using a record trigger flow instead of using apex code for complex business requirements. Sometimes we have requirements that can not be accomplished using standard validation rules. So you can use this approach instead of developing before insert apex trigger.
Some of the limitations in the standard validation rules are mentioned below.
- You can not reference PRIORVALUE function on a field from lookup values such as Parent.RecordType.DeveloperName.
- You can not reference the related records data in validation rules, such as related activity history.
Now let’s say we have a business requirement that before an opportunity is marked as closed won, the opportunity must have at least one contact role and we are going to accomplish this via record trigger flow + validation rule without a single line of coding.
STEP 1:
Since our rule should run when an opportunity is marked as closed won. So first create a checkbox field on the opportunity object and set the default value as unchecked. Make sure to not add the field to the page layouts.
STEP 2
Created a record trigger flow that should configure to run when an opportunity stage is updated to closed won. See attached screenshot.
Then add a Get Records element to the flow and get the related opportunity contact roles as shown in the following screenshot.
Now using the decision element check, if no opportunity contact roles are found then update the checkbox field (created in step 1) to true.
STEP 3
Create a validation rule on the opportunity object, that should run when the checkbox field is checked and throw an error message. The validation rule formula is copied below.
AND(
At_Least_one_OCR_Validation__c = TRUE,
ISCHANGED(At_Least_one_OCR_Validation__c)
)
STEP 4
Once you have completed all the above steps, make sure to activate the record trigger flow created in step 2 and activate the validation rule created in step 3.
The validation rule will automatically trigger whenever the opportunity stage is updated. Because if you look at the Salesforce Order of Execution, when the before trigger flow runs and update the checkbox field, the custom validation rules are triggered again to verify all the required fields have a non-null value.