I have setup a trigger to update a custom checkbox Attachment__c on opportunity on uploading or deletion of file as an attachment. This seems to work fine on the file upload but fails every time on deletion of the attached file. Please let me know if I am making any mistake. Thanks in advance for help!
Please find the code below:
trigger OppAttachmentTrigger2 on ContentDocument (after insert,after update) {
if(Trigger.isAfter && Trigger.isInsert ||Trigger.isAfter && Trigger.isUpdate){
Set<Id> IdCollect = new Set<Id>();
for(ContentDocument att:Trigger.New){
if(att.ParentId!=null){
IdCollect.add(att.ParentId);
}
}
List<Opportunity> oppList = new List<Opportunity>();
for(Opportunity oppy : [SELECT Id,Attachment__c FROM Opportunity where id=:IdCollect]){
for(ContentDocument at:Trigger.New){
if(at.ParentId!=null){
oppy.Attachment__c = true;
oppList.add(oppy);
}
}
}
update oppList;
}
// After delete attachment///
if(Trigger.isBefore && Trigger.isDelete){
Set<Id> IdCollect = new Set<Id>();
for(ContentDocument att:Trigger.Old){
system.debug('--att '+att);
if(att.id!=null){
IdCollect.add(att.Id);
}
}
List<ContentDocumentLink> cdl = new List<ContentDocumentLink>();
cdl = [SELECT Id,LinkedEntityId FROM ContentDocumentLink WHERE ContentDocumentId IN :IdCollect ];
system.debug('ContentDocumentLink ---- cdl '+cdl);
List<Opportunity> oppList = new List<Opportunity>();
for(Opportunity oppy : [SELECT Id,Attachment__c FROM Opportunity where id=:IdCollect]){
oppList.add(oppy);
oppy.Attachment__c = false;
}
update oppList;
} }