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
rameshramesh 

how to fetch role and subordinates underhim for apex contrler

how to fetch role and subordinates underhim for apex contrler 
SubratSubrat (Salesforce Developers) 
Hello Ramesh ,

This is the sample code for your requirement :
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);

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.
Arun Kumar 1141Arun Kumar 1141

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:
 
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];
    }
}

Hope this will be helpful.
Thanks!