Background: I'm trying to write a handler class to create Chatter group members, I have a future method that works great for one group. However, my requirement is three groups and that's where it goes off the rails.
When it runs I get an the error:
Insert failed. First exception on row 3; first error: DUPLICATE_VALUE, User is already a Member of this group.: [MemberId]
Doing some debugs it wants to create 9 records, 3 sets of the 3 groups.
How can I loop through each object and add member records for each user/group combination?
@future
public static void addToGroups(Set<Id> userIds)
{
// The users that will be added to the group
List<User> users = [SELECT id, Username FROM User WHERE id in :userIds];
// Find the Chatter group Ids from the names of the custom setting "Chatter Auto Follow"
List<CollaborationGroup> chatterGroups = [SELECT Id, Name
FROM CollaborationGroup
WHERE Name in :Chatter_Auto_Follow__c.getall().keySet()];
// Get Chatter values
List<Chatter_Auto_Follow__c> settings = [SELECT Name, Frequency__c FROM Chatter_Auto_Follow__c];
// Create blank lists for inserting new records
List<CollaborationGroupMember> chatterGroupMembers = new List<CollaborationGroupMember>();
// loop the users that have been created
for (User u : users)
{
// loop the custom setting records
for(Chatter_Auto_Follow__c s : settings)
{
// loop the groups
for (CollaborationGroup c : chatterGroups)
{
// add the user to the group
CollaborationGroupMember cMember = new CollaborationGroupMember(
CollaborationGroupId = c.id,
MemberId = u.Id,
CollaborationRole = 'Standard',
NotificationFrequency = s.Frequency__c
);
chatterGroupMembers.add(cMember);
}
}
}
System.debug('Members To Insert:: ' + chatterGroupMembers);
insert chatterGroupMembers;
}