0

Currently I have this code on VFP

<apex:commandButton value="Edit" action="{!Edit}" 
   rendered="{!(($Profile.Name =='System Administrator'||$Profile.Name =='Sales Manager'))}"  />

But I want to move away from VFP to APEX code instead.

How can I translate what I have in VFP to APEX code?

I have tried something like this:

//get the user id:
string u = Userinfo.getUserId(); 
//profile
list<profile> profile = [select id,name from profile where id  =:u limit 1];
system.debug('///'+profile); //get the empty

3 Answers 3

1

You are querying the wrong table with the UserInfo data. UserInfo.getUserId gets you a User Id, so Query the User table instead of Profile table. From there you can fetch the profile name.

//get the user id:
string u = Userinfo.getUserId(); 
//profile
list<User> users = [select id,name, profile.Name from User where id  =:u limit 1];
system.debug('///'+users); 

By the way: I'd recommend using a hierarchy custom setting for functionality like this. That way you can maintain the set of profiles without changes to the code.

4
  • actually using profileId directly is better (see Nick's answer). Commented Jul 19, 2016 at 15:52
  • I like the idea of creating custom setting, so you will add all the profile name in the custom setting and you compare against it? I understand the custom setting but I'm not sure how would you go after that in sense validating which user has which profile access, please share if you can little bit more
    – Nick
    Commented Jul 19, 2016 at 16:07
  • Create a hierarchy custom setting named e.g. 'special authorizations'. Then a checkbox field called 'viewEditButton'. Then set the default value (org-wide setting) of the custom setting to 'false' and add entries for the specific profiles for which it's allowed containing a 'true'. Then access the custom setting from VF page or code Commented Jul 19, 2016 at 16:52
  • Actually 'Custom Permissions' is the final solution for this, but it doesn't support VisualForce or Validation Rules yet. Can only be used in APEX currently. Commented Jul 19, 2016 at 16:55
6

You're querying the profile with the ID of the user, which will never work.

You can get the ProfileID by using UserInfo.getProfileID();

0

You can query on User record to fetch the profile name of a logged in User.

List<User> userList = [Select Id, Name, ProfileId, Profile.Name from User where Id=: UserInfo.getUserId() limit 1];

System.debug('##'+userList[0].Profile.Name);

You must log in to answer this question.

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