[SalesForce] How to access all the public groups relatedto an user in apex

I am trying to find out all the public groups related to an user and display it on a vf page. Is this doable?

Step 1: from Groupmember I get the group Id related to a user using

list<groupmember> g_m = [select id from groupmember where userorgroupid =: userid];

Step 2: I query all the group info

This gives me only a subset of groups of type ="Regular". How do I access all the Public Groups related to a user.

I also want to display the groups that the user is related to as part of nesting (ie) if user A is related to public group A and public group A is nested within Public group B the user becomes part of Public group B to which I want visibility into .

Any help would be greatly appreciated.

Best Answer

that will do the trick. what you basically have to do is to traverse through the nested groups by self referencing the getGroupsForIds() method

// return list of all groups the user belongs to via direct or indirect membership
public Group[] getGroupsForUser(Id userId){

    Set<Id> groupIds = getGroupsForIds(new Set<Id>{userId});
 return [
   select Id
        , Name
     from Group
    where Id IN: groupIds];

}

// return all ids the user belongs to via direct or indirect membership
public Set<Id> getGroupsForIds(Set<Id> userOrGroupIds){

    Set<Id> output = new Set<Id>();

    Set<Id> nestedGroupIds = new Set<Id>();

    // only query actual groups and not roles and queues
    list<GroupMember> records = [
        select id
             , GroupId
             , UserOrGroupId
          from GroupMember
         where UserOrGroupId =: userOrGroupIds
        and UserOrGroupId != null
           and Group.Type = 'Regular'];

    for (GroupMember record:records)
    {
        // found a group, remember for traversal
        if (!(record.UserOrGroupId + '').startsWith('005'))
        {
            nestedGroupIds.add(record.UserOrGroupId);   
        }
        else
        {
            output.add(record.GroupId);
        }
    }

    // call self to get nested groups we found
    if (nestedGroupIds.size() > 0)
    {
        output.addAll(getGroupsForIds(nestedGroupIds));
    }

    return output;
}
Related Topic