15

What is the right way to get the current users profile in an apex class?

When I tried to print the following in visualforce page, i am able to get the profile name

<apex:outputText value="{!$Profile.Name}"/> 

But when i tried to print in the Apex class using System.debug(Profile.Name), I couldn't.

29
Id profileId=userinfo.getProfileId();
String profileName=[Select Id,Name from Profile where Id=:profileId].Name;
system.debug('ProfileName'+profileName);

Refer the above code

7

I know I'm coming late to this party, but I solved this for my particular case by doing the following;

  1. define a formula field (named, say, "CurrentUserProfile) on an object that has this code:
    $UserProfile.Name

  2. In your trigger (or class), you can just refer to the variable from the object;

     for(Task t :triggerNew) {
     // ...
     System.debug('Current User Profile: ' + t.CurrentuserProfile__c);
     // ...
     }
    

Hope this helps.... You can do the same for the Role name too.

  • 2
    I just want to point out for other readers that this solution is overkill. No need to create a custom formula field on each object when Apex already has a built in class to deliver user information (ie the UserInfo class). – smohyee Jul 24 '15 at 21:26
  • But UserInfo does NOT have that info...that's the point. That's why the marked answer needs another soql call...For system performance and user response time this answer is far better than the above mentioned as it uses an existing dml call to get the missing info. – Schnaps Jan 21 at 11:47

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.