I want to change the owner of the file(ContentDocument) uploaded to a case to the owner of the case.
trigger ContentDocumentLinkTrigger on ContentDocumentLink (after insert)
{
List<ContentVersion> versionsToUpdate = new List<ContentVersion>();
Map<Id,Id> contentDocIdToCaseId = new Map<Id,Id>();
Map<Id, Case> mpCase = new Map<Id, Case>();
Map<Id,ContentVersion> contentMap = new Map<Id,ContentVersion>();
for(ContentDocumentLink cdl : Trigger.new )
{
System.debug('UAC cdl ' + cdl );
if(String.valueOf(cdl.LinkedEntityId).startsWith('500'))
{
contentDocIdToCaseId.put(cdl.ContentDocumentId, cdl.LinkedEntityId);
}
}
System.debug('UAC contentDocIdToCaseId ' + contentDocIdToCaseId );
mpCase = new Map<Id, Case>([SELECT Id, OwnerId FROM Case WHERE Id IN: contentDocIdToCaseId.values()]);
for(ContentVersion cv : [SELECT Id, OwnerId, ContentDocumentId FROM ContentVersion WHERE ContentDocumentId IN :contentDocIdToCaseId.keySet() AND IsLatest = True])
{
contentMap.put(cv.ContentDocumentId, cv);
}
System.debug('UAC mpCase ' + mpCase );
System.debug('UAC contentMap ' + contentMap );
for(ContentDocumentLink cdl : Trigger.new )
{
String caseId = cdl.LinkedEntityId ;
if(mpCase.containsKey(caseId) && contentMap.containsKey(cdl.ContentDocumentId) )
{
ContentVersion cv = contentMap.get(cdl.ContentDocumentId);
cv.OwnerId = mpCase.get(caseId).OwnerId ;
versionsToUpdate.add(cv);
}
}
if(versionsToUpdate.size() > 0) update versionsToUpdate ;
}