Loading

Fetch public groups for a user via Apex

Date de publication: Oct 13, 2022
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.
Résolution
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])
{
	grRoleMap.put(gr.relatedId,gr.id);
}

//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')])
{
	groupwithUser.add(u.groupId);
}

//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
	if(grRoleMap.containsKey(u.UserRoleId))
	{
		results.add(grRoleMap.get(u.UserRoleId));
	}
}
//Combining both the Set
results.addAll(groupwithUser);

//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')])
{
	grMap.put(gr.UserOrGroupId,gr.Groupid);
}
for(Id i :results)
{
	if(grMap.containsKey(i))
	{
		results.add(grMap.get(i));
	}
}

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

NOTE: The code provided is an example. Please review and make modifications for your organization.
 
Numéro d’article de la base de connaissances

000387341

 
Chargement
Salesforce Help | Article