I am trying to add user to a chatter group from apex. I am getting an error
"Error [statusCode=INVALID_CROSS_REFERENCE_KEY, code=[xmlrpc=1202, statusCode=INVALID_CROSS_REFERENCE_KEY, exceptionCode=INVALID_CROSS_REFERENCE_KEY, scope=PublicApi, http=400], message=This user can't be added to the group., fields=null]"
Here is the code i am using
lstCGM.add(new CollaborationGroupMember(CollaborationGroupId = lCGA[k].Chatter_Group_ID__c ,
// CollaborationRole = 'Member',
MemberId = u[i].Id ));
//Debugging
for(CollaborationGroupMember cgmr : lstCGM)
{
system.debug('Processing the CGM record ' + cgmr);
}
if (lstCGM.size() > 0)
{
// Insert the CGM Records
Database.SaveResult[] lsr = Database.insert(lstCGM, false);
// Loop through the save results writing errors to the debug log
for (Database.SaveResult sr : lsr)
{
if(!sr.IsSuccess())
{
Database.Error err = sr.getErrors()[0];
System.debug(err.getMessage());
}
} // END LOOP through the save results writing errors to the debug log
}// END IF there are records to insert, insert them.
The debug logs return the correct ids
Processing the CGM record CollaborationGroupMember:{CollaborationGroupId=0F9E00000008cpwKAA, MemberId=005c0000000R2kQAAS}
USER_DEBUG|[275]|DEBUG|This user can't be added to the group.
Checked the ids on the browser and they were valid. Any idea what should be causing this?
UPDATE
This code on a after insert trigger on user.
Attribution to: Prady
Possible Suggestion/Solution #1
Most probably this comes because of invalid foreign key reference, please make sure that userId and Group Id are pointing to correct records. Also Is any of the object group or user deleted ?
By the way I tried a simplistic code with a couple of user license types, its working fine
Id grpId = '0F990000000Tgwv';
Id usrId = '00590000000dmJF';
insert new CollaborationGroupMember(
CollaborationGroupId = grpId,
MemberId = usrId);
The above code produces the same error if I try to add a user to a deleted group
19:42:52:041 FATAL_ERROR System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []
Attribution to: Abhinav Gupta
Possible Suggestion/Solution #2
The reason for this error was that users with Chatter External license are considered as customers and these users cannot be added to a public group.
They can only be added to private group and with allow customers checked.
Hope this helps others who run into this issue.
Attribution to: Prady
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/1190