Print this page

Fetching Public Groups for a User via Apex

Knowledge Article Number 000211729
Description In a scenario,when we need to fetch all the Public group related to a particular User via Apex, we can use the below sample code given in the solution.
Resolution In a org,we can have 3 types of Group related to User 
  1.  Direct Groups : The group which contains the  User as Group Member
  2.  Indirect Groups : It can be of 2 Types :-
    1. Groups with Roles : The Group which contain Role of User as the Group Member
    2. Nested Groups : The Group which contain another Group as Group Member of which the User is part of.
I have tried to cover all the requirements and the below sample code would work for each one of them :-
//Declaring a Set as we don't want Duplicate Group Ids
Set<Id> results = new Set<Id>();

///Declaring a Map for Group with Role
Map<Id,Id> grRoleMap = new Map<Id,Id>();

//Populating the Map with RelatedID(i.e.UserRoledId) as Key
for(Group gr : [select id,relatedid,name from Group])

//Groups directly associated to user
Set<Id> groupwithUser = new Set<Id>();

//Populating the Group with User with GroupId we are filtering only  for Group of Type Regular,Role and RoleAndSubordinates
for(GroupMember  u :[select groupId from GroupMember where UserOrGroupId='<User Id>' and (Group.Type = 'Regular' OR Group.Type='Role' OR Group.Type='RoleAndSubordinates')])

//Groups with Role
for(User  u :[select UserRoleId from User where id='<User Id>'])
	//Checking if the current User Role is part of Map or not
//Combining both the Set

//Traversing the whole list of Groups to check any other nested Group
Map<Id,Id> grMap = new Map<Id,Id>();
for(GroupMember gr : [select id,UserOrGroupId,Groupid from GroupMember where
        (Group.Type = 'Regular' OR Group.Type='Role' OR Group.Type='RoleAndSubordinates')])
for(Id i :results)

system.debug('########' + results);


promote demote