Activity › Forums › Salesforce® Discussions › Is there a way to Query Salesforce Role Hierarchy?
Tagged: Parent Role, Parent Role Id, Role Hierarchy, Salesforce Apex, Salesforce Apex Code, Salesforce Query, Salesforce SOQL, User Roles
-
Is there a way to Query Salesforce Role Hierarchy?
Posted by Nitish on April 14, 2016 at 9:26 AMI’d like to query for all UserRoles under the same Parent Role.
The only way I can think of doing this is by querying all Roles, then putting together a tree using the ParentRoleId field. Is there a better way?
Divya replied 7 years, 6 months ago 3 Members · 2 Replies -
2 Replies
-
Hi Nitish,
Try the below code.U just need to pass the user id to this class and it chugs through all of the level beneath that User in the role hierarchy and returns the IDs of all of the users in those roles:
public with sharing class RoleUtils { public static Set<ID> getRoleSubordinateUsers(Id userId) { // get requested user’s role Id roleId = [select UserRoleId from User where Id = :userId].UserRoleId; // get all of the roles underneath 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 so you can do what you want with them return users.keySet(); } private static Set<ID> getAllSubRoleIds(Set<ID> roleIds) { Set<ID> currentRoleIds = new Set<ID>(); // get all of the roles underneath the passed roles for(UserRole userRole :[select Id from UserRole where ParentRoleId IN :roleIds AND ParentRoleID != null]) currentRoleIds.add(userRole.Id); // go fetch some more rolls! if(currentRoleIds.size() > 0) currentRoleIds.addAll(getAllSubRoleIds(currentRoleIds)); return currentRoleIds; } }Code Source: http://blog.jeffdouglas.com/2011/02/15/find-my-salesforce-users-by-role-hierarchy
Thanks.
- [adinserter block='9']
-
Hi Nitish
Try this:
public class Utility { // To get all sub roles. public static Set<ID> getAllSubRoleIds(Set<ID> roleIds) { Set<ID> currentRoleIds = new Set<ID>(); // get all of the roles underneath the passed roles for(UserRole userRole :[select Id from UserRole where ParentRoleId IN :roleIds AND ParentRoleID != null]) { currentRoleIds.add(userRole.Id); } // go fetch some more rolls! if(currentRoleIds.size() > 0) { currentRoleIds.addAll(getAllSubRoleIds(currentRoleIds)); } return currentRoleIds; } // To get all Parent Roles. public static Set<ID> getParentRoleId(Set<ID> roleIds) { Set<ID> currentRoleIds = new Set<ID>(); // get all of the parent roles. for(UserRole ur :[select Id, ParentRoleId from UserRole where Id IN: roleIds]) { currentRoleIds.add(ur.ParentRoleId); } // go fetch some more rolls! if(currentRoleIds.size() > 0) { currentRoleIds.addAll(getParentRoleId(currentRoleIds)); } return currentRoleIds; } }
Log In to reply.