+ Start a Discussion
Bernd BretzelmannBernd Bretzelmann 

Can't share document with group via trigger

Hello,
I'm fairly new to coding and I want to create a trigger where I share a document with a certain chatter group automatically and give them contributer rights when I upload a file via the chatter feed.This is how my trigger looks like:

trigger publishFileToGroup on ContentDocumentLink (after insert) {

  List<CollaborationGroup> chattergroup = [SELECT Id FROM CollaborationGroup WHERE Name = 'Apex Trigger Group'];  
  List<ContentDocument> documents = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument];

  ContentDocumentLink cdl = New ContentDocumentLink(
 
  LinkedEntityId = chattergroup[0].Id, ContentDocumentId = documents[0].Id, shareType = 'C');
 
  insert cdl;

}

This doesn't work and the following error message appears:
"Apex trigger publishFileToGroup caused an unexpected exception, contact your administrator: publishFileToGroup: execution of AfterInsert

caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, publishFileToGroup: execution of AfterInsert

caused by: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Document with ID: 06958000000Aejh is already linked with the entity with ID: 0F9580000005tul: Linked Entity ID: [LinkedEntityId]

From my understanding it says that the document is already linked with the chatter group, which is not true. Any ideas?


 
MedhanieHabteMedhanieHabte
I definitely would recommend checking the debug log to see the process in action, perhaps include system.debug statement to see what may be occurring, you can also run a SOQL query on attachments too and check the id's to see what may be going on.