I created a trigger that copies all incoming email-to-case attachments to Files so that users can select these's files when forwarding emails etc. The code I have so for is:
trigger CaseAttachment on Attachment (after insert) {
Set<Id> Parents = new Set<Id>();
for (attachment a : Trigger.New) {
Parents.add(a.parentId);
}
for (EmailMessage e : [SELECT Id, ParentId FROM EmailMessage WHERE Id in :Parents]) {
for (Attachment a : Trigger.New) {
if (e.Id == a.ParentId) {
Case c = [SELECT Id, CaseNumber FROM Case WHERE id =: e.ParentId LIMIT 1];
ContentVersion cv = new ContentVersion();
cv.ContentLocation = 'S';
cv.PathOnClient = a.Name;
cv.Origin = 'H';
cv.OwnerId = a.OwnerId;
cv.Title = a.Name+'-'+c.CaseNumber;
cv.VersionData = a.Body;
insert cv;
ContentVersion cov = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =: cv.Id];
ContentDocumentLink cl = new ContentDocumentLink(LinkedEntityId = e.ParentId, ContentDocumentId = cov.ContentDocumentId, ShareType = 'V');
insert cl;
}
}
}
}
When creating Files and linking them to records we need to create a ContentVersion first, and then link it to a record by creating a ContentDocumentLink. Right now I'm doing all the inserts in my loop because I cant think of a way to ContentVersion Ids any other way. I tried doing something like this:
trigger CaseAttachment on Attachment (after insert) {
Set<Id> Parents = new Set<Id>();
List<ContentVersion> newFiles = new List<ContentVersion>();
List<ContentDocumentLink> newFileLink = new List<ContentDocumentLink>();
for (attachment a : Trigger.New) {
Parents.add(a.parentId);
}
for (EmailMessage e : [SELECT Id, ParentId FROM EmailMessage WHERE Id in :Parents]) {
for (Attachment a : Trigger.New) {
if (e.Id == a.ParentId) {
ContentVersion cv = new ContentVersion();
cv.ContentLocation = 'S';
cv.PathOnClient = a.Name;
cv.Origin = 'H';
cv.OwnerId = a.OwnerId;
cv.Title = a.Name;
cv.VersionData = a.Body;
cv.ExternalDocumentInfo1 = e.ParentId;
newFiles.add(cv);
}
}
}
insert newFiles;
for (ContentVersion cov : newFiles) {
ContentDocumentLink cl = new ContentDocumentLink(LinkedEntityId = cov.ExternalDocumentInfo1, ContentDocumentId = cov.ContentDocumentId, ShareType = 'V');
newFileLink.add(cl);
}
insert newFileLink;
}
I'm looking to fetch the correct ContentVersions by adding the Case Id to a field, in this case ExternalDocumentInfo1. This doesn't seem to work however.