+ Start a Discussion
ChappyChappy 

how to find a users subordinates

Hi,

 

I am trying to find records that are owned by a user or anyone beneath them in the role hierarchy.

 

 

Can anyone suggest a way to do this in apex.

 

Thanks,

Chappy

Best Answer chosen by Admin (Salesforce Developers) 
aalbertaalbert

You can find out the user's subordinates from the UserRole object. Find the user's role , then you will have to loop across the UserRole object to find all the roles that have that user's role as the ParentRoleId and so on until you find the lowest node of the hierarchy. That will give you a list of RoleIds. From there, you have to query for all Users that have one of those RoleIds. Lastly, you query the sObject type filtering by OwnerId. 

 

How big is your role hierarchy? Since that is a loop, you will want to be careful how many times you iterate.  

All Answers

aalbertaalbert

You can find out the user's subordinates from the UserRole object. Find the user's role , then you will have to loop across the UserRole object to find all the roles that have that user's role as the ParentRoleId and so on until you find the lowest node of the hierarchy. That will give you a list of RoleIds. From there, you have to query for all Users that have one of those RoleIds. Lastly, you query the sObject type filtering by OwnerId. 

 

How big is your role hierarchy? Since that is a loop, you will want to be careful how many times you iterate.  

This was selected as the best answer
ChappyChappy

Thanks for the reply,

 

I was hoping there would be a better way to do it, our role hierarchy is about 12 levels deep.

 

 

CloudHugger2CloudHugger2

Looping across that many levels just means pull all roles into a map first.

 

Then, starting with the first level find its subordinate levels, add to a set, then loop through that set and so on - even at 50 levels deep you'll still have only queried the UserRole table once.

 

At the end of the iterations you'll have a set of UserRoles that you can do one last query for all users whose roleId is in the set you've generated.

 

Hope that helps.