public with sharing class Utility {
//Get all sub roles.
public static Set<ID> getRoleSubordinateUsers(Id userId) {
//Get requested user's role Id
Id roleId = [SELECT UserRoleId From User Where Id = :userId].UserRoleId;
//Get all of the roles below the user
Set<Id> allSubRoleIds = getAllSubRoleIds(New Set<ID>{roleId});
// get all of the ids for the users in those roles
Map<Id, User> users = new Map<Id, User>([SELECT Id, Name From User Where UserRoleId IN :allSubRoleIds]);
//Return the ids as a set
return users.keySet();
}
//Get all Parent Roles.
private static Set<ID> getAllSubRoleIds(Set<ID> roleIds) {
Set<ID> currentRoleIds = new Set<ID>();
//Get all of the roles below the passed roles
for(UserRole userRole :[SELECT Id from UserRole Where ParentRoleId IN :roleIds AND ParentRoleID != null]){
currentRoleIds.add(userRole.Id);
}
//Fetch more rolls
if(currentRoleIds.size() > 0){
currentRoleIds.addAll(getAllSubRoleIds(currentRoleIds));
}
return currentRoleIds;
}
}
Call the getRoleSubordinateUsers method of the above class by passing User Id in it.
Id userId = UserInfo.getUserId();
Set<Id> allUsersId = Utility.getRoleSubordinateUsers(userId);
To fetch the role and subordinates under a specific user in an Apex controller, you can use the Salesforce User and UserRole objects. You can achieve this as follows:
public class UserRoleController {
public User currentUser { get; set; }
public List<User> subordinates { get; set; }
public UserRoleController() {
// Fetch the current user
currentUser = [SELECT Id, Name, UserRoleId, UserRole.Name FROM User WHERE Id = :UserInfo.getUserId()];
// Fetch the subordinates under the current user's role
subordinates = [SELECT Id, Name, UserRoleId, UserRole.Name FROM User WHERE UserRoleId = :currentUser.UserRoleId];
}
}
This is the sample code for your requirement : Call the getRoleSubordinateUsers method of the above class by passing User Id in it.
Reference : https://www.biswajeetsamal.com/blog/find-all-users-below-a-role-in-role-hierarchy/
If this helps , please mark this as Best Answer.
Thank you.
Hi Ramesh,
To fetch the role and subordinates under a specific user in an Apex controller, you can use the Salesforce User and UserRole objects. You can achieve this as follows:
Hope this will be helpful.
Thanks!