1

I have a requirement of getting accounts with respect to role heirarchy. For eg. Lets say there are 3 roles A,B,C. Now when A user logins i want to fetch all the records of A,B,C user, similarly if B user logins, then i want only records owned by B and C and so on. How can i achieve this. Can i just write a normal query and make my class as with sharing? Will that work or is there anything we need to do?

Any help would be appreciated. Thanks

2 Answers 2

0

Can i just write a normal query and make my class as with sharing?

Provided the object's sharing settings are configured to grant access using hierarchies in Setup, yes, you should simply run SOQL in a with sharing context and take advantage of the system's built-in visibility controls.

Generally reimplementing record visibility in Apex should be a last resort. Do everything possible to harness out-of-the-box sharing and visibility functionality first.

0

A simple query will provide you with the desired results only if the OWD for account is set to Private and there aren't any permissive permission settings on the Account object. If it's less restrictive than that, your visibility doesn't depend on role hierarchy you could retrieve more records than just those owned by the running user and his subordinates. If that's the case, you'd want to write a more sophisticated code to fetch the accounts where the owner is either the running user or his role subordinates.

You can write this recursive method to retrieve all the IDs of the roles of the running user's subordinates:

public static Set<ID> getAllMySubRoleIds(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;

  }

Then call it from your code, which would be something like this:

public List<Account> getMyRoleSubordinatesAccounts(){

   //grab all role id's under running user in hierarchy
   Set<ID> allRoleIds = getAllMySubRoleIds(new Set<ID>{UserInfo.getUserRoleId()});

    //make sure to add the current running user's role as well
   allRoleIds.add(UserInfo.getUserRoleId());  

   //retrieve all accounts owned by the roles collected
   return [SELECT Id
           FROM Account
           WHERE Owner.UserRoleId in :allRoleIds];  
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .