How to find hierarchical manager in salesforce

Hello everyone recently I got requirement to give permission which is based on manager hierarchy in apex.

Lets discuss how to achieve this.

The tricky part to achieve this is to find set of user who are all in manager hierarchy for particular user.

Here is the code to find manager hierarchy for particular user.

List<Id> ParentUserId=new List<Id>();
ParentUserId.add('User id');// Add user Id to whom you want to find manager herarichy 
getParrentId('User id');// If you want to add base user also add this line else no need
public static void getParrentId(Id userId){    
    User userDetails = new User();
    userDetails = [select Id, Name, ManagerId from User  where Id =: userId];
    if(userDetails.ManagerId != null){        
        getParrentId(userDetails.ManagerId);// Recursive call to find manager of manager

Now we got collection of user id's who need's permission.

Let give them permission using there user id's.

Happy coding :)

No votes yet