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
SunnyShinySunnyShiny 

Trigger check if current user is admin

Hello,

 

How can I check if the current user firing the trigger is admin or not?

 

Thanks

Best Answer chosen by Admin (Salesforce Developers) 
ssssssssssssss

You can get the current user's profile using UserInfo.getProfileId().  Then you can look up the profile name via SOQL and see if it is 'System Administrator'.

 

 

And if you just want to make sure that whatever the profile of the logged in user, the code should always run as system admin, try to use RunAs:

 

public class TestRunAs {
   public static testMethod void testRunAs() {
      // Setup test data
      // This code runs as the system user Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; User u = new User(Alias = 'standt', Email='standarduser@testorg.com', EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = p.Id, TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.com'); System.runAs(u) { // The following code runs as user 'u' System.debug('Current User: ' + UserInfo.getUserName()); System.debug('Current Profile: ' + UserInfo.getProfileId()); } } }

All Answers

hitesh90hitesh90

compare with current user profile... is system administrator or not

ssssssssssssss

You can get the current user's profile using UserInfo.getProfileId().  Then you can look up the profile name via SOQL and see if it is 'System Administrator'.

 

 

And if you just want to make sure that whatever the profile of the logged in user, the code should always run as system admin, try to use RunAs:

 

public class TestRunAs {
   public static testMethod void testRunAs() {
      // Setup test data
      // This code runs as the system user Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; User u = new User(Alias = 'standt', Email='standarduser@testorg.com', EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = p.Id, TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.com'); System.runAs(u) { // The following code runs as user 'u' System.debug('Current User: ' + UserInfo.getUserName()); System.debug('Current Profile: ' + UserInfo.getProfileId()); } } }
This was selected as the best answer