5

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.

1 Answer 1

11

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;
}
3
  • @seb_Wanger I am getting all the regular groups, but how do I get all the groups related to an user through nesting,does this code take care of all the nesting?I am using relatedtoID =: userrole that pulls in roles and queues. How do I get all the type of types of public groups described here :salesforce.com/us/developer/docs/api/Content/…
    – Rao
    Jul 2, 2013 at 17:45
  • 1
    if you dont want to limit the groups by type, just get rid of 'and Group.Type = 'Regular'];' in the SOQL query
    – Seb Wagner
    Jul 2, 2013 at 21:30
  • Awesome reference to self-reference! Jan 16, 2014 at 14:28

You must log in to answer this question.

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