According to Salesforce Help:
Validation rules verify that the data a user enters in a record meets the standards you specify before the user can save the record. A validation rule can contain a formula or expression that evaluates the data in one or more fields and returns a value of “True” or “False”. Validation rules also include an error message to display to the user when the rule returns a value of “True” due to an invalid value.
Hierarchy Custom Settings is a type of custom setting that uses a built-in hierarchical logic that lets you “personalize” settings for specific profiles or users. The hierarchy logic checks the organization, profile, and user settings for the current user and returns the most specific, or “lowest,” value. In the hierarchy, settings for an organization are overridden by profile settings, which, in turn, are overridden by user settings.
When to use?
You have Validation Rules which have to be customized based on Profile or User. Because of that, you had to hard code Names and Id’s. That’s a bad practice!
Users should be prevented from changing the Stage after the Opportunity has been closed. Only System Administrators and one User should bypass the Validation Rule.
Instead of hard coding Profile or User Names, Id’s, you need to configure a Hierarchy Custom Setting.
Configure Hierarchy Custom Setting (in Lightning Experience)
- Go to Setup -> Custom Code -> Custom Settings.
- Create new Hierarchy Custom Setting.
- For each Validation Rule you want to bypass, you need to create a checkbox field (1). You can also create one checkbox field per object, if you want to bypass all Validation Rules (2).
- In the Custom Fields section select: New -> Checkbox -> Enter Field Label, Field Name -> Save.
- Click Manage and configure Validation Rule Configuration based on Profiles and Users.
- Configure Default Organization Level Value Setting. Click New and check all checkboxes. It means that all Validation Rules are respected.
- Configure settings for Profiles and Users. Click New in the section below the Default Organization Level Value. Choose Location and which Validation Rules will be respected by checking the checkboxes.
Update all Validation Rules which you want to bypass
Remove all hard coded Id’s and Names and add Hierarchy Custom Setting values.
Validation Rules in Unit Tests
If you want to respect Validation Rules in Unit Tests, you need to insert Custom Setting values.
I want to fire Cannot_Change_Stage_After_Close Validation Rule in System Administrator context. In the TestSetup or before update the Opportunity you need to add:
Profile sysAdminProfile = [SELECT Id FROM Profile WHERE Name = 'System Administrator']; insert new VRConfiguration__c(SetupOwnerId = sysAdminProfile.Id, Opp_Cannot_Change_Stage_After_Close__c = true);