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
Brijesh KumarBrijesh Kumar 

how can get current user's profile name in apex class.

Hi
can you tell me what is the method for getting current user's profile name in apex class.
 
In visualforce page, we can use    {!$Profile.Name}  
 
 
 
it gives current profile name but i want a relavant method  in apex code.
 
Thanks & Regards
Brijesh Kumar Baser
 
hisrinuhisrinu
Hi Brijesh,


You can get like this
id id1 = userinfo.getProfileId()
Then
select Name from profile where id = :id1;



Brijesh KumarBrijesh Kumar

Hi hisrinu

Thanks for your reply.It's greate for me.

 

Thanks & Regards

Brijesh Kumar Baser

Suresh RaghuramSuresh Raghuram

Id id1 = UserInfo.getProfileId();
System.debug('******************Profile ID' +id1);
String profileName = [Select Name from Profile where Id = ' id1'];

 

But i am getting the following error

Error: Compile Error: invalid ID field: id1 at line 9 column 30

If i Put : after = It is saying illegal assigenment from List

 

Colud you please correct me whee i am making error

NagothiNagothi

Can you change the following line

String profileName = [Select Name from Profile where Id = ' id1'];

 

to this 

String profileName = [Select Name from Profile where Id =: id1];

 

and let me know?

zachbarkleyzachbarkley

Complete Working Code:

 

List<Profile> PROFILE = [SELECT Id, Name FROM Profile WHERE Id=:userinfo.getProfileId() LIMIT 1];
String MyProflieName = PROFILE[0].Name;

 

RESULT: System Administrator

Luong TamLuong Tam
Profile p = [Select Name from Profile where Id =: userinfo.getProfileid()];
String pname = p.name;
kevin Carotherskevin Carothers
If you don't want to burn a SOQL Statement and you're working with an SObject, you can use this approach:

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

2.   In your trigger, you can refer to the variable;
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.