Tuesday, August 12, 2014

Small Utilities Method


Hi friends, I am back from long time, in between this I could not get a chance to post anything new.
In this post I am showing you small utility methods which we use everyday. This can help if you are looking any quick tip or help -
Map mapOfUserRole = new Map([SELECT Id, Name, ParentRoleId FROM UserRole]);
Map mapOfUserRoleWithHierarchy = new Map();

public void processRoles(){
  String level = '';
  List ListOfUserRole = [SELECT Name, Id FROM UserRole];
  if(ListOfUserRole != NULL && ListOfUserRole.Size()>0){
   for(UserRole u:ListOfUserRole){
    level = processParentRole(u.Id,'');
    if(level != ''){
     mapOfUserRoleWithHierarchy.put(u.Id,level);
     
    }
   }
  }
 }
 
public String processParentRole(Id role, String hierarchyString){
  UserRole userrole = mapOfUserRole.get(role);
  if(userrole.ParentRoleId != NULL){
   hierarchyString += '>>' + userrole.Name;
   return  processParentRole(userrole.ParentRoleId,hierarchyString);  
  }else{
   hierarchyString += '>>'+userrole.Name;
   return hierarchyString;
  }
 }
 
processRoles();
here if you debug mapOfUserRoleWithHierarchy map you will see something like below -
00EXXXXXXXX=>>Team1>>Team2>>Team3>>Team4>>CEO
here I am assuming that hierarchy in your system something like
    -CEO
       -Team4
          -Team3
             -Team2
                -Team1     
Hope this can help if you are doing some code & need something related to user role hierarchy! will keep adding other util method in this post so this can be used kind of quick reference:)