If your Salesforce org has Triggers and Apex, you’ve probably run into the issue of hitting Validation Rules (VRs) when your Apex code tries to insert or update a record. The example below is across two objects and how you can solve for it.
Let’s say you have an object called Positions and another object called Applicants. There is a lookup field on Applicants to the Position object. On the Positions object, you have a date field called Last Interview Date to identify the latest date an applicant was interviewed. Due to the relationship between Applicants and Positions only being a Lookup and not a Master-Detail, you can’t use Rollup Summary fields to get the MAX of the Interview Date field on the Applicants object.
To solve for this, you write a Trigger and Apex class on the Applicants object to query all Applicants for the related Position record and find the Applicant with the MAX Interview Date, then populate that date in the Last Interviewed Date field on the Positions object.
Let’s say there’s a validation rule on Position that requires the Hire By field to be greater than the current day if the Status is not On Hold or Closed. This is to require users to extend the Hire By date to a more accurate date if the position was not filled by the current day the record is being updated.
With the above validation rule, the code that updates the Position record with the Interview Date from the Applicant record will fail due to the Validation Rule. Applicants still need to be created and updated and the Apex that updates the related Position still needs to process. In order to allow this, we need to put in a custom solution to bypass validation rules from Apex.
The solution for this is to create a Checkbox field called Bypass Apex on the object that your Apex is updating. In this case, it will be on the Position object. The field should not be on any page layouts. Be sure to update your Apex populating the Positions Last Interview Date and add a line to set Bypass Apex to true.
Update your Validation Rule on the Positions object to include Bypass_Apex__c = false. This will prevent the Validation Rule from firing when your Apex is updating the Last Interview Date.
Next, we need to create a workflow rule that evaluates if the Bypass Apex field is checked, and if so a workflow field update to uncheck the Bypass Apex field on Positions so that end users still get an error on subsequent updates.
Lastly, we create our Workflow Field update.
Even though this scenario was more complex than most due to it being cross object, you can still use this same design on a single object when you want to bypass Validation Rules from Apex.
We’re Salesforce experts that would love to work with you. Email us and we’d love to talk.