I've been stumped for awhile on this issue, although I believe there should be something very simple I can do!

I am building a custom controller for a Visualforce page and one function I am building is passed a userID where I then need to find that specific user's UserRoleId, then collect a set of roles under their role, and then select a list of subordinate users, seen below:

public static List<user> fetchUsersTeamMembers(Id userId){

    List<user> userA = [select Id, UserRoleId From User where Id=:userId LIMIT 1];
    Set<Id> allSubRoleIds = new Set<Id>();
    If(userA[0] != null){
        allSubRoleIds = getAllSubRoleIds(new Set<ID>{userA[0].UserRoleId});

    List<user> userList = [select u.LastName,Name,u.Id, u.FirstName,u.Email
                          From User u where profile.Name='AMS Sales User' 
                          and isActive=true and (Id=:userId or UserRoleId 
                          in:allSubRoleIds) order by u.FirstName];

    return userList.size()>0 ? userList : new List<user>();

public static  Set<ID> getAllSubRoleIds(Set<ID> roleIds) {
    Set<ID> currentRoleIds = new Set<ID>();
    for(UserRole userRole :[select Id from UserRole where ParentRoleId  
         IN :roleIds AND ParentRoleID != null]) {
    if(currentRoleIds.size() > 0) {
    return currentRoleIds;

There are no errors on save, but I am getting a List Index out of bounds error when trying to view my page.

First, Is there a more elegant solution to get the UserRoleId from the UserId, perhaps with a direct query on UserRoleId or even without SOQL?

If not, Do you see where my mistake is?

1 Answer 1

If(userA[0] != null){

This works in JavaScript, but in Apex Code, if the list is empty, you'll get an exception. Instead, check if the list is empty:

if(!userA.isEmpty()) {

You must log in to answer this question.

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