Thursday, March 23, 2017

Apex Trigger On AttachmentObject to Check Has_Attachment(Checkbox Field) in CaseObject when Attachment is Attached to CaseObject and Un Check when attachments are deleted.

 Trigger on Attachment to Check Case have Attachment or Not,If attachment is there then checking a checkbox field in Case,If no attachments are there then making that checkbox false.

Trigger:

trigger TriggerOnAttachement on Attachment (after insert,after delete){
    if(trigger.isinsert){
        Cls_Update_has_attachement_case.UpdatefieldinCasetocheck(trigger.New);
    }
    if(trigger.isdelete){
        Cls_Update_has_attachement_case.UpdatefieldinCasetoUncheck(trigger.old);
    }
}


Class:

public class Cls_Update_has_attachement_case{
    Public static void UpdatefieldinCasetocheck(List<Attachment> atts){
        List<Id> ParentId = new List<Id>();
        List<Case> listCase = new List<Case>();
        for (Attachment attachmentObject: atts)
        {
            ParentId.add(attachmentObject.ParentId);
        }
        List<Case> Caselist = [Select Id,Has_Attachment__c from Case where Id IN:ParentId ];
        if(Caselist!=null && Caselist.size()>0){
            for(Case cs : Caselist){
                cs.Has_Attachment__c = true;
                listCase.add(cs);
            }
        }
        if(listCase.size() > 0)
            update listCase;  
    }
 
    Public static void UpdatefieldinCasetoUncheck(List<Attachment> atts){
        List<Id> ParentId = new List<Id>();
        List<Case> listCase = new List<Case>();
        for (Attachment attachmentObject: atts)
        {
            ParentId.add(attachmentObject.ParentId);
        }
        List<Case> csToUpdate=new List<Case>();
        for(case cs:[Select Id,Has_Attachment__c,(SELECT Id FROM ContentDocumentLinks),(SELECT Id FROM attachments) FROM Case where ID In:ParentId]){
            system.debug('size of atts===>'+cs.ContentDocumentLinks.Size());
            if(cs.ContentDocumentLinks.Size()==0 && cs.Has_Attachment__c==True && cs.attachments.Size()==0 ) {
                cs.Has_Attachment__c=false;
                csToUpdate.add(cs);
            }
        }
        system.debug('csToUpdate===>'+csToUpdate);
        if(!csToUpdate.isEmpty())
            Database.update(csToUpdate, false);
    }
}

No comments:

Post a Comment