How to retrieve the list of users based on role hierarchy

How to retrieve the list of users based on Role Hierarchy in Salesforce?

How to retrieve the list of users based on Role Hierarchy in Salesforce: Sometimes, you need a multilevel hierarchy i.e. you need to view the individual data/reports of all the employees who are working under you. So, you need to find all the users directly under a role and its sub-roles in the role hierarchy. Here is what I have written a sample piece of code which will be easier for you to get users on the basis of the role.

Controller:

public class hierarchialInfoController{
    public Id currentUserId{get;set;} // To get the id of current User(logged-in User)
    public Id currentUserRoleId{get;set;}
    public User loggedInUser{get;set;}
    public set<Id> usersIds{get;set;}
    public hierarchialInfoController(){        
        // Get the id of the current user.        
        currentUserId = UserInfo.getUserId();
        // Get the role id of the current user.         
        currentUserRoleId = UserInfo.getUserRoleId();
        usersIds = new set<Id>();
        loggedInUser = [Select id, Name from User where Id=:currentUserId];
    }
    // Method to return the list of users on the basis of role hierarchy.
    public List<SelectOption> getUsersList() {
        List<SelectOption> userList = new List<SelectOption>();
        userList.add(new SelectOption(loggedInUser.Id,loggedInUser.Name));
        usersIds.add(loggedInUser.Id);
        // roleHierarchyUtilityClass is the utility class which returns the list of users which are below the role of Current User.
        Set<Id> allUsers = roleHierarchyUtilityClass.getRoleSubordinateUsers(currentUserRoleId); 
        for(User usr : [Select id, name from User where id =:allUsers]){
            userList.add(new SelectOption(usr.id, usr.Name));
            usersIds.add(usr.Id);
        }
        return userList;
    }
}

Helper Class:

public with sharing class roleHierarchyUtilityClass {
    public static Set<ID> getRoleSubordinateUsers(Id roleId) {
        // To get all sub roles.
        Set<Id> allSubRoleIds = getAllSubRoleIds(new Set<ID>{roleId});
        Map<Id,User> users = new Map<Id, User>([Select Id, Name From User where IsActive = True AND UserRoleId IN :allSubRoleIds]);
        return users.keySet();
    }
    
    public static Set<ID> getAllSubRoleIds(Set<ID> roleIds) {
        Set<ID> currentRoleIds = new Set<ID>();
        // Get all the roles underneath the passed roles.
        for(UserRole userRole :[select Id from UserRole where ParentRoleId IN :roleIds AND ParentRoleID != null])
            currentRoleIds.add(userRole.Id);
        if(currentRoleIds.size() > 0){
            currentRoleIds.addAll(getAllSubRoleIds(currentRoleIds));
        }
        return currentRoleIds;
    }
}

Hope this will help you a lot to understand the role hierarchy in APEX.

Thanks for reading

Hail Salesforce.

Popular Salesforce Blogs