Bypass Apex Trigger using Custom Permission - Apex Basic | Salesforce Funda



Custom Permissions let you define access checks that can be assigned to users via permission sets or profiles, similar to how you assign user permissions and other access settings

A custom permission is a specific attribute added to a Permission Set. This attribute allows you to apply a specific logic to any user being assigned this permission set.

To Check in Apex Syntax :- 

Boolean hasCustompermission = FeatureManagement.checkPermission('your_custom_permission_api_name');

To use Custom Permission :-

To use custom permissions in Apex triggers, you can follow these steps:

  • Create a Custom Permission:
  1. Go to "Setup" in Salesforce.
  2. In the Quick Find box, search for "Custom Permissions" and click on it.
  3. Click on the "New Custom Permission" button.
  4. Provide a Label and a Name for the custom permission.
  5. Save the custom permission.
  • Assign Custom Permission to User Profiles or Permission Sets:
  1. In the Quick Find box, search for "Profiles" or "Permission Sets" depending on whether you want to assign the custom permission to a user profile or a permission set.
  2. Open the desired profile or permission set.
  3. Find the "Custom Permissions" section and click on "Edit".
  4. Add the custom permission you created to the enabled permissions list.
  5. Save the changes to the profile or permission set.
  • Check Custom Permission in Apex Trigger:
  1. Open the Apex trigger where you want to check for the custom permission.
  2. Inside the trigger code, use the FeatureManagement.checkPermission method to check if the custom permission is enabled for the user. This method returns a Boolean value indicating whether the permission is enabled or not.

User case :- We have a user case we need to bypass trigger for the user who have specific custom permission assign in there assigned permission set in the user assigned profile

trigger code :-
trigger ContactDemo on Contact (before Delete) {
 
   if(trigger.isBefore && trigger.isDelete){
   Boolean hasCustomPermission = FeatureManagement.checkPermission('Bypass_Account_Validation');
    if(hasCustomPermission){
        System.debug('Deleted');
       }else{
        for(Contact con : trigger.old){
            con.addError('you cant delete the Contact, you dont have permission');
       }
      }
    }
  }

Error message show :-

when we don't have custom permission assigned to the User Profile we get this error



when we have custom permission assigned we can easy bypass trigger and able to delete it


Note :- for creating Custom Permission and Permission set and assign to user you can check the below post and go with the step by step tutorials