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
Hanna BergsmaHanna Bergsma 

Trigger Not Creating ContentDocumentLink

I have a (simple i thought???) trigger that creates a contentdocumentlink between an email attachment and the parent case of the email.

The CDL is not being created, thus the caseid is not a linkedentityid on that contentdocumentId. where am I going wrong?

Im thinking maybe this is actually trying to update/insert on a link that already exists and im not actually creating a new link??
trigger relateEmailFileToParentCase on EmailMessage (after insert) {
 	for (EmailMessage EM : Trigger.new){
        if (EM.HasAttachment == TRUE )  {
         
	list<ContentDocumentLink> docLinks = [Select Id, ContentDocumentId  from ContentDocumentLink where LinkedEntityId = :EM.id ];
    List<ContentDocumentLink> listLinks = new List<ContentDocumentLink>();
    Case parentCase = [SELECT Id from Case where Id=: EM.ParentId];

            for(ContentDocumentLink docLink : doclinks){
            docLink.Visibility = 'AllUsers';
            docLink.LinkedEntityId = parentCase.id;
            docLink.ShareType = 'V';
            docLink.ContentDocumentId = doclinks[0].ContentDocumentId;
            listLinks.add(docLink);          
        }
            insert listLinks;
      }
	}
}

 
Hanna BergsmaHanna Bergsma
Ive since made some edits but still no dice. it is not creating the new link to the case
 
trigger relateEmailFileToParentCase on EmailMessage (after insert) {
    List <ContentDocumentLink> linksToInsert = new List<ContentDocumentLink>();
 	for (EmailMessage EM : Trigger.new){
        if (EM.HasAttachment == TRUE )  {
        
            ContentDocumentLink cdl = new ContentDocumentLink();
            Case parentCase = [SELECT Id from Case where Id=: EM.ParentId];
            list<ContentDocumentLink> docLinks = [Select Id, ContentDocumentId from ContentDocumentLink where LinkedEntityId = :EM.id];
            
            for(ContentDocumentLink docLink : docLinks){
            cdl.Visibility = 'AllUsers';
            cdl.LinkedEntityId = parentCase.id;
            cdl.ShareType = 'V';
            cdl.ContentDocumentId = docLinks[0].ContentDocumentId;
            linksToInsert.add(docLink); 

		}
	}
}
}