17

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.

2 Answers 2

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

Refer the above code

9

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.

3
  • 3
    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
    Commented Jul 24, 2015 at 21:26
  • 1
    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
    Commented Jan 21, 2020 at 11:47
  • What you are proposing is a tradeoff where on 1 side is: - +1 SOQL query in quite possibly specific use case for: - having to maintain 1 extra field and having that field recalculated whenever SF runs recalculateFormulas, worse readability and maintainability as you dont have clear separation of concerns, domains etc. In most cases that tradeoff is not worth it :) Commented Jun 17 at 12:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .