Prady
Prady

Reputation: 11320

Get all roles under current users role

I am trying to get all the roles under the current logged in users role. We dont know the levels in the hierarchy, it would change depending on the logged in user.

Any pointers on how we can achieve this on a generic way

  currentUserRoleId= userInfo.getUserRoleId();

I want to see all the roles under currentUserRoleId and the roles under each level.

Thanks

Upvotes: 0

Views: 6475

Answers (1)

John Sullivan
John Sullivan

Reputation: 1311

Unfortunately, there does not appear to be a pre-built way to do this. However, you should be able to write code to do it recursively like so:

public static set<Id> getSubordinateRoles(Id roleId) {
    map<Id, set<Id>> parentAndChildren = new map<Id, set<Id>>();
    set<Id> children;
    for(UserRole ur : [select Id, ParentRoleId from UserRole]) {
        children = parentAndChildren.containsKey(ur.ParentRoleId) ? parentAndChildren.get(ur.ParentRoleId) : new set<Id>();
        children.add(ur.Id);
        parentAndChildren.put(ur.ParentRoleId, children);
    }
    return getSubordinateRoles(role, parentAndChildren);
}

public static set<Id> getSubordinateRoles(Id roleId, map<Id, set<Id>> parentAndChildren) {
    set<Id> subordinateRoles = new set<Id>();
    set<Id> remainingSubordinateRoles = new set<Id>();
    if(parentAndChildren.containsKey(roleId)) {
        subordinateRoles.addAll(parentAndChildren.get(roleId));
        for(Id subRoleId : subordinateRoles) {
            remainingSubordinateRoles.addAll(getSubordinateRoles(subRoleId, parentAndChildren));
        }
    }
    subordinateRoles.addAll(remainingSubordinateRoles);
    return subordinateRoles;
}

I haven't tested this, so let me know if it doesn't work.

Upvotes: 3

Related Questions