1

I'm writing a simple trigger to prevent deletion of opportunities that are marked Receivable. (Code below.) Could you help me add a criteria to allow deletion if the user doing so is a sysadmin? I assume I need to add something in the for criteria where I've put a blank, but not sure of the syntax there.

trigger OpportunityBeforeDelete on Opportunity (before delete) {
for  (Opportunity q: trigger.old)
    if (q.Receivable__c == true && __________________ ){
        q.adderror('Receivable opportunities should not be deleted. Receivable opportunities can only be deleted by a system administrator.');
    } 
}
2

You can verify the running User, if System Admin, then don't restrict the deletion. Something as below should work.

String profileName = [select Name from profile where id = :UserInfo.getProfileId()].Name;

for(Opportunity q: trigger.old) {

    if (q.Receivable__c == true && profileName != 'System Administrator'){
        q.adderror('Receivable opportunities should not be deleted. Receivable opportunities can only be deleted by a system administrator.');
    }
} 
0

You will want to add a line using this:

userInfo.getProfileId()

Then you can either hardcode the ID of the system admin profile by retrieving it via dev console or you can add a query to get the profile's name and compare it against System Administrator like below:

Profile PROFILE = [SELECT Id, Name FROM Profile WHERE Id=:userinfo.getProfileId() LIMIT 1];
If(PROFILE.Name == 'System Administrator'){
    //Logic here
}
0

An alternative approach you may want to consider is using custom permissions instead of profiles.

The steps are

  1. Create a custom permission say 'bypass trigger'
  2. Assign this to a permission set
  3. Give necessary users this permission set.

In Apex trigger you can check if a running user has this permission with below syntax

Boolean hasCustomPermission = FeatureManagement.checkPermission('bypass trigger');

if (!hasCustomPermission) {
    // Allow triggercode
}

The advantage of this code is tomorrow if you want to extend this for another user you just add the permission set to the user and it will work without any code changes.

Also if you wish to remove for system admin you just remove this permission set from the user and then the trigger will fire for them as well without any code changes.

Lesser maintenance and more configuration controlled way to manager trigger bypasses.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.