function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
JamsieJamsie 

How do you get the context of the running user in a Trigger

Hi everyone.

 

I wish to grant a group of users the Manage Cases permission.  However, I do not want to allow them to delete Cases. Therefore, I have written a Trigger (see code below) to constrain the delete Case permission to Sys Admins and the API.  This works well when users work through the GUI.

 

However, when the users click on a custom button which causes a custom controller to delete a Case they are returned the error from the Trigger.

 

I can see that it is my call to  UserInfo.getProfileId(); that is causing the problem. 

 

Is there any way to know that the Trigger is has been called from within a controller an therefore permit the deletion?

 

Many thanks,

James.

 

trigger preventUnauthorisedCaseDeletion on Case (before delete) {

    System.debug('-- Prevent Case Deletion | Trigger Called');

    List<String> pNames = new List<String>{'System Administrator', 'APIOnly'};
    List<Profile> profiles = new List<Profile>([select id, Name from Profile where name in :pNames]);

    for(Case c : Trigger.old){
        Boolean authorised=false;        
        Id userProfileId = UserInfo.getProfileId();
        System.debug('-- Prevent Case Deletion | Current User: ' + UserInfo.getName());
        for(Profile p : profiles){
            if(userProfileID == p.Id){
                authorised = true;
                System.debug('-- Prevent Case Deletion | Current User OK: ' + UserInfo.getName());
                break;
            }
        }
        if(!authorised){
            System.debug('-- Prevent Case Deletion | Current User UNAUTHORISED: ' + UserInfo.getName());
            c.addError('You do not have sufficient permission to delete a Case. If you have good reason to have this Case deleted please raise a Helpdesk incident.');
        }
    }
}

 

dmchengdmcheng

It seems like it would be easier to detect the current user in the custom controller and do nothing if not a sys admin.  Remove the Delete permission on the Case object in the users' profile and then you don't need the trigger at all.