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
Ashish PWPAdminAshish PWPAdmin 

If I have UserRole Name , then how to fetch ID for it in Apex

If I have UserRole Name , then how to fetch ID for it in Apex. This is not for current user info
Best Answer chosen by Ashish PWPAdmin
Arun Kumar 1141Arun Kumar 1141
Hi, 
You can try the below code
String userRoleName = 'System Admin'; 
Id userRoleId;
List<UserRole> userRoles = [SELECT Id FROM UserRole WHERE Name = :userRoleName LIMIT 1];
if (userRoles.size() > 0) {
  userRoleId = userRoles[0].Id;
}

OR
String userRoleName = 'System Admin'; 
List<Id> userRoleIdList;
List<UserRole> userRoles = [SELECT Id FROM UserRole WHERE Name = :userRoleName];
for(UserRole userId :userRoles){
    userRoleIdList.add(userId.Id);
}

For more info check on the below link
https://developer.salesforce.com/forums/?id=9060G0000005SXxQAM
Please mark as Best Answer if above information was helpful.
Thanks
 

All Answers

VinayVinay (Salesforce Developers) 
Hi Ashish,

You can try below snippet.
Id userRoleId = UserInfo.getUserRoleId();
System.debug('User Role ID: ' + userRoleId);
getUserRoleId() method only returns a value when the organization-wide role hierarchy is enabled.

Please mark as Best Answer if above information was helpful.

Thanks,
Arun Kumar 1141Arun Kumar 1141
Hi, 
You can try the below code
String userRoleName = 'System Admin'; 
Id userRoleId;
List<UserRole> userRoles = [SELECT Id FROM UserRole WHERE Name = :userRoleName LIMIT 1];
if (userRoles.size() > 0) {
  userRoleId = userRoles[0].Id;
}

OR
String userRoleName = 'System Admin'; 
List<Id> userRoleIdList;
List<UserRole> userRoles = [SELECT Id FROM UserRole WHERE Name = :userRoleName];
for(UserRole userId :userRoles){
    userRoleIdList.add(userId.Id);
}

For more info check on the below link
https://developer.salesforce.com/forums/?id=9060G0000005SXxQAM
Please mark as Best Answer if above information was helpful.
Thanks
 
This was selected as the best answer
Ashish PWPAdminAshish PWPAdmin

@vinay

I do not want the Role Id for Logged in User. I want the Role id where the Role name is being passed as a string

Ashish PWPAdminAshish PWPAdmin

@arunkumar

thanks your 1st code snippet works