I wanted to post a solution just in case someone visits this thread in future. For delete, according to an unpublished salesforce article, The trigger needs to be on ContentDocument instead of ContentDocumentLink object. For my particular scenario, I needed to add an error message if a user tries to delete a file attached to an inventory record which is in Final stage. trigger ContentDocTrigger on ContentDocument (before delete) {
//get prefix of Inventory exception record
Schema.DescribeSObjectResult inv = Inventory_Exception__c.sObjectType.getDescribe();
String invKeyPrefix = inv.getKeyPrefix();
List<Id> contentDocId = new List<Id>();
Map<Id, Id> contDocLinkedMap = new Map<Id, Id>();
if(trigger.IsDelete){
for(ContentDocument con : Trigger.old){
System.debug(Trigger.old);
System.debug(con.Id);
contentDocId.add(con.Id);
}
for(ContentDocumentLink cdl : [SELECT ContentDocumentId, LinkedEntityId FROM ContentDocumentLink WHERE ContentDocumentId IN : contentDocId]){
contDocLinkedMap.put(cdl.ContentDocumentId, cdl.LinkedEntityId);
System.debug('map ' +contDocLinkedMap);
}
for(ContentDocument cdoc : Trigger.Old){
//contDocLinkedMap.get(cdoc.Id) will give the LinkedEntityId
if(invKeyPrefix == String.valueOf(contDocLinkedMap.get(cdoc.Id)).left(3) &&
[select status__c from Inventory_Exception__c where id = :contDocLinkedMap.get(cdoc.Id)].status__c =='Final'){
cdoc.adderror('This attachment could not be added because this exception record is marked as Final.');
}
}
}
}
4 answers