Was looking into a blog post of jeff douglas on FIND MY SALESFORCE USERS BY ROLE HIERARCHY, its an awesome utility code for fetching the child users in the hierarchy, so thought of righting a same kind of code to get all the parent users in current user's hierarchy, when I started writing it then I realized it is not that much easily, have to give some time to it.
So here I am, below is the code for fetching the Parent user's id in hierarchy, the method will the return a map of user on the key and the set of Id's of the parent user in the values.
Happy Coding!!
So here I am, below is the code for fetching the Parent user's id in hierarchy, the method will the return a map of user on the key and the set of Id's of the parent user in the values.
1:public static Map<Id, Set<Id>> getRoleParentSubordinateUsers(Set<Id> userId) {
2: Map<Id, Id> roleIds = new Map<Id, Id>();
3: Map<Id, Set<Id>> parentRoleIds = new Map<Id, Set<Id>>();
4: // get requested user's role
5: for(User usr : [select Id, UserRoleId from User where Id IN: userId and UserRoleId != null]) {
6: roleIds.put(usr.UserRoleId, usr.Id);
7: }
8: Map<Id, Set<Id>> parentids = new Map<Id, Set<Id>>();
9: for(Id ids : roleIds.keySet()) {
10: parentRoleIds.put(ids, getAllParentRoleIds(new Set<ID>{ids}));
11: }
12: for(Id kys : parentRoleIds.keySet()) {
13: for(Id ids : parentRoleIds.get(kys)) {
14: if(!parentids.containsKey(ids)) {
15: parentids.put(ids, new Set<Id>{kys});
16: } else {
17: parentids.get(ids).add(kys);
18: }
19: }
20: }
21: Map<Id, Set<Id>> mapOfCurrentWithParentUsers = new Map<Id, Set<Id>>();
22: // get all of the ids for the users in those roles
23: for(User us : [Select Id, Name, Region__c, State__c, UserRole.Name, UserRoleId From User where IsActive = true AND (UserRoleId IN: parentids.keySet() OR UserRoleId IN :roleIds.keySet())]){
24: for(Id rids : parentRoleIds.keySet()) {
25: if(parentids.containsKey(us.UserRoleId)){
26: if(parentids.get(us.UserRoleId).contains(rids)) {
27: if(!mapOfCurrentWithParentUsers.containsKey(roleIds.get(rids))) {
28: mapOfCurrentWithParentUsers.put(roleIds.get(rids), new Set<Id>{us.id});
29: } else {
30: mapOfCurrentWithParentUsers.get(roleIds.get(rids)).add(us.Id);
31: }
32: }
33: }
34: }
35: }
36: // return the ids as a set so you can do what you want with them
37: return mapOfCurrentWithParentUsers;
38: }
39: private static Set<Id> getAllParentRoleIds(Set<ID> roleIds) {
40: Set<ID> mapOfCurrentWithParentRole = new Set<Id>();
41: // get all of the roles underneath the passed roles
42: for(UserRole userRole :[select Id, ParentRoleID from UserRole where Id IN :roleIds AND ParentRoleID != null])
43: mapOfCurrentWithParentRole.add(userRole.ParentRoleID);
44: // go fetch some more rolls!
45: if(mapOfCurrentWithParentRole.size() > 0){
46: mapOfCurrentWithParentRole.addAll(getAllParentRoleIds(mapOfCurrentWithParentRole));
47: }
48: return mapOfCurrentWithParentRole;
49: }
Happy Coding!!