get all the users in role heirachy apex

Many times we come across requirement where we need to get all the roles/users below the logged in users role.
Following piece of code gives you all the roles below in hierarchy of current logged in users role.
Example:  Just press the button to get all the Roles below in role hierarchy.

Visualforce page



  1. Hi Yoganand,

    Please ,can you make me understand the below snippet:
    for(UserRole userRoleName :[select Id,name from UserRole where ParentRoleId = :UserRole AND ParentRoleID != null]){


    I didnot understand ' = :UserRole'

    What is :UserRole here? And where you are making reference query, because we have used ':'.

  2. Why do we use .addAll, why not .add? Any special benefit of using .addAll?

  3. Hi,
    How pareneRoleId =: UserRole?

    select Id,name from UserRole where ParentRoleId = :UserRole

  4. I am new to apex. So, it would be extremely helpful sir, if you comments your code. So that we can understand from the basic. Thank you.

  5. Really its working Nice .but its failed when page has multiple parent ids....