I am working on an requirement to assign users to chatter groups when they are new or edited to meet a criteria. One part is looking for existing CollaborationGroupMembers to see if there is an existing group member as you cannot insert members that already exist.
The problem is I cannot figure out how to return records and then send only the ids for the ones that do not exist to the method to create the member record.
I have this bit that works for one group at a time but with my expected 3 groups it errors in the future method if the user is already in one of the group.
First error: Insert failed. First exception on row 1; first error: DUPLICATE_VALUE, User is already a Member of this group.: [MemberId]
public static void matchExisting(Set<Id> userIds)
{
// Find the Chatter group Ids from the names of the custom setting "Chatter Auto Follow"
List<CollaborationGroup> chatterGroups = [SELECT Id
FROM CollaborationGroup
WHERE Name in :Chatter_Auto_Follow__c.getall().keySet()];
// Query for existing chatter group records
List<CollaborationGroupMember> cGMember = [SELECT Id,
MemberId,
CollaborationGroupId
FROM CollaborationGroupMember
WHERE MemberId IN :userIds AND
CollaborationGroupId IN :chatterGroups];
System.debug('member size is:: ' + cGMember.size());
if(cGMember.size() == 0)
{
addToGroups(userIds);
}
}
EDIT:
Once I have a list of users to add to the group then I have this method to do the work of adding the group:
@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>();
List<FeedItem> feedPosts = new List<FeedItem>();
// 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('chatter members to insert is:: ' + chatterGroupMembers);
insert chatterGroupMembers;
}