function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SF7SF7 

Adding Users to Public Groups

I need to add users with ceratin profile to be automatically  added to a public group . Any hints plz

Best Answer chosen by Admin (Salesforce Developers) 
SF7SF7

trigger addintoPublicgroup on User (after insert) {
   AddUser.AddToGroups(trigger.newMap.keySet());

}

 

//This class is refrenced in the apex trigger Add to Group in order to add users automatically to public groups.
public class AddUser{

@future
public static void AddToGroups(Set<Id> userIds)
{
 //Get the groups that the user should be added to
Group g=[select Id from Group Where DeveloperName='test'];

 List<User> users=[Select Id,Name from user Where Id IN :userIds];
 
 List<GroupMember>listGroupMember =new List<GroupMember>();  
 // loop the users that have been created
 for (User user : users){
      GroupMember gm= new GroupMember(); 
      gm.GroupId=g.id;
      gm.UserOrGroupId = user.id;
      listGroupMember.add(gm);   
 } 
 insert listGroupMember;
}
}

All Answers

sai.sfsai.sf

create a new GroupMember object

set the GroupId to your group id

set the UserOrGroupId to the user id

insert into the database (or store in a list for later insertion if there are a few of them, to avoid governor limit probs).

Jia HuJia Hu
Make a after insert trigger on the User
Monitor the user with certain profile, and add this user to a certain public group with the UserID
SF7SF7

trigger addintoPublicgroup on User (after insert) {
   AddUser.AddToGroups(trigger.newMap.keySet());

}

 

//This class is refrenced in the apex trigger Add to Group in order to add users automatically to public groups.
public class AddUser{

@future
public static void AddToGroups(Set<Id> userIds)
{
 //Get the groups that the user should be added to
Group g=[select Id from Group Where DeveloperName='test'];

 List<User> users=[Select Id,Name from user Where Id IN :userIds];
 
 List<GroupMember>listGroupMember =new List<GroupMember>();  
 // loop the users that have been created
 for (User user : users){
      GroupMember gm= new GroupMember(); 
      gm.GroupId=g.id;
      gm.UserOrGroupId = user.id;
      listGroupMember.add(gm);   
 } 
 insert listGroupMember;
}
}

This was selected as the best answer
AshishyadavAshishyadav
Getting this error when iam trying to implement your code
Error: Compile Error: line 8:47 no viable alternative at character '​' at line 8 column 47
SF7SF7
Cam u specify the line where u r getting error by posting ur code
Roger WickiRoger Wicki
@ashish.saleforce@live.com

Always use single quotes ' and ' instead of double quotes " and " in Apex.
Barsha BiswasBarsha Biswas
what if there are several groups and we need to assign different user to different group based on some criteria - like country of the user ? any idea on that please 
Roger WickiRoger Wicki
@Barsha Biwas

I would recommend the following:
  • Create a Custome Metadata
  • Add all assignments for your criteria (like CountryCode => Group.DeveloperName)
  • Write a code that hands the criteria (e.g. CountryCode) to the mapping of the Custom Metadata and assign the group that way.
Example (to put in either a trigger or a class called by the trigger):
map<String, Id> groups = new map<String, Id>();
map<String, String> groupMapping = new map<String, String>();
list<GroupMember> groupMembers = new list<GroupMember>();

// Create mapping from the Group's Developer Name to its ID
for ( Group g : [SELECT Id, DeveloperName FROM Group] ) {
  groups.put(g.DeveloperName, g.Id);
)

/** Assuming your Custom Metadata is called GroupMapping and has the criteria in
*   MasterLabel and the value in a custom metadata custom field called GroupName
*/
for ( GroupMapping__mdt mapping : [SELECT MasterLabel, GroupName FROM GroupMapping__mdt] ) {
  groupMapping.put(mapping.MasterLabel, mapping.GroupName);
}

// Replace <YourCriteriaField> with the field that marks your criteria, e.g. CountryCode as you suggested
for ( User u : trigger.new) {
  if ( groupMapping.containsKey(u.<YourCriteriaField> ) {
    groupMembers.add(new GroupMember(UserOrGroupId = u.Id, GroupId = groups.get(groupMapping.get(u.<YourCriteriaField>))));
  }
  // Optionally add an else clause to handle non-assignable users like maybe add them to a default group
}

insert groupMembers;
The advantage of this is if you have a new requirement for mappings and/or new Groups, all you need to do is to change/extend the Custom Metadata mapping, without touching any code.

Best
Roger
Barsha BiswasBarsha Biswas
Hi Roger,

Thanks for the solution , however my code doesnt add any group to the new user created 

Here is my code 
public class AddUser2 {
    
public static void AddtoGroup(Set<id> userIds)
    {
        map<String, Id> groups = new map<String, Id>();
        map<String, String> groupMapping = new map<String, String>();
        list<GroupMember> groupMembers = new list<GroupMember>();
        list <user> users = [select id,name,User_Group__c from user where id IN : userIds];



        for ( Group g : [SELECT Id, DeveloperName FROM Group] ) {
            groups.put(g.DeveloperName, g.Id);
        }
        
        
        for ( GroupMapping__mdt mapping : [SELECT MasterLabel, GroupName__c  FROM GroupMapping__mdt] ) {
            groupMapping.put(mapping.MasterLabel, mapping.GroupName__c );
        }
        
        for (user u: users){
            
            if (groupMapping.containsKey(u.User_Group__c))
                {
                     groupMembers.add(new GroupMember(UserOrGroupId = u.Id, GroupId = groups.get(groupMapping.get(u.User_Group__c))));
                }
        }
                	insert groupMembers;
    }
    
}
Trigger 
trigger AddToGroup on User (after insert) {
AddUser2.AddtoGroup(Trigger.newmap.keyset());
}

GroupName__c is the custom field on the metatdata type 

User_Group__c is the criteria field on user object which is a multislect picklist

I havent worked with metadata types earlier , so I am sure i am making some mistake here 

Please help
 
Barsha BiswasBarsha Biswas
Hi Roger 

I got this to work !

Actually using the DeveloperName instead of the GroupName__c in Metadata query resolved the issue , since the API names were referred everywhere else 

I can now add to different groups based on my criteria 

Thanks Again!

Barsha 
Roger WickiRoger Wicki
@Barsha Biwal

Did you add the mappings to the Custom Metadata? For that you have to go to Setup > Develop > Custom Metadata Types and click on Manage Records next to your Custom Metadata. There you have to create every entry where you put a value from User_Group__c to the Label and the DeveloperName of the corresponding group to the GroupName__c field.

As for the User_Group__c multi-select picklist field on user: Do you expect it to work that as soon as it contains a specific value from the multi-select picklist, it is added to that group accordingly? As in:
User a has as User_Group__c: A; B; D; G; K
And he is supposed to be added to all of these groups (If one thinks of one group per letter here)?
Where another user has User_Group__c: A; C, D; E
And is supposed to be added to these groups?

If so you will have to split the String of the mutli-select picklist and do a for loop on the user as well. I never worked with multi-select picklists in Apex before so I don't know how they work. But I'm sure you can make use of the String.split(<delimiter>) method.
Roger WickiRoger Wicki
Ah good, I was apparently too late with my answer :)
Barsha BiswasBarsha Biswas
Yes I did add the mappings to the custom metadata . But I had not set the group name with developer name which caused the issue , i have resolved this now

And yes , i do intend to make it work like you said --User a has as User_Group__c: A; B; D; G; K And he is supposed to be added to all of these groups 

Thanks for suggesting a work around around that , i will try and it