Retrieve the Users below a certain Role in Role Hierarchy #inSalesforce
public with sharing class theRoleRetrieve {
public static Set<ID> getUnderneathRole(Id userId) {
Id roleId = [SELECT UserRoleId From User Where Id = :userId].UserRoleId;
Set<Id> underneathRoleIds = getunderneathRoleIds(New Set<ID>{roleId});
Map<Id, User> users = new Map<Id, User>([SELECT Id, Name From User Where UserRoleId IN :underneathRoleIds]);
return users.keySet();
}
private static Set<ID> getunderneathRoleIds(Set<ID> roleIds) {
Set<ID> mainRoleIds = new Set<ID>();
for(UserRole userRole :[SELECT Id from UserRole Where ParentRoleId IN :roleIds AND ParentRoleID != null]){
mainRoleIds.add(userRole.Id);
}
if(mainRoleIds.size() > 0){
mainRoleIds.addAll(getunderneathRoleIds(mainRoleIds));
}
return mainRoleIds;
}
}
public static Set<ID> getUnderneathRole(Id userId) {
Id roleId = [SELECT UserRoleId From User Where Id = :userId].UserRoleId;
Set<Id> underneathRoleIds = getunderneathRoleIds(New Set<ID>{roleId});
Map<Id, User> users = new Map<Id, User>([SELECT Id, Name From User Where UserRoleId IN :underneathRoleIds]);
return users.keySet();
}
private static Set<ID> getunderneathRoleIds(Set<ID> roleIds) {
Set<ID> mainRoleIds = new Set<ID>();
for(UserRole userRole :[SELECT Id from UserRole Where ParentRoleId IN :roleIds AND ParentRoleID != null]){
mainRoleIds.add(userRole.Id);
}
if(mainRoleIds.size() > 0){
mainRoleIds.addAll(getunderneathRoleIds(mainRoleIds));
}
return mainRoleIds;
}
}
Test by calling the above method may be in anonymous window:
Id userId = UserInfo.getUserId();
Set<Id> underneathRoles = theRoleRetrieve.getUnderneathRole(userId);
system.debug('!!!!!!!!!!underneathRoles!!!!!!!!!!!'+underneathRoles);
Set<Id> underneathRoles = theRoleRetrieve.getUnderneathRole(userId);
system.debug('!!!!!!!!!!underneathRoles!!!!!!!!!!!'+underneathRoles);
Comments
Post a Comment