function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SFDC9999SFDC9999 

Trigger to get Attachment ID on to the parent Object

I am trying to get the latest attachment id on to the case object fields based on the Name of the document . I have 2 fields on cases ( A,X)and If an attachement is added to case with the name ABC then its Id should be filled in Filed A on case and if Attachment is added with Name XYZ then Field X on the case should be filled with the ID of XYZ. If there are mutiple attachments with the same name then we should take the latest attachment.
 
trigger CaseAttachment on Attachment (before insert) {  
   Boolean isCaseAttachment = FALSE;    
      List<Case> Cases = new List<Case>();  
        Set<Id> accIds = new Set<Id>();  
        for(Attachment att : trigger.New){  
             /*Check if uploaded attachment is related to Case Attachment and same Case is already added*/  
             if(att.ParentId.getSobjectType() == Case.SobjectType && (!accIds.contains(att.ParentId)) && att.Name.contains('XYZ')){  
                  //prepare a Case object for update  
                  Cases.add(  
                                      new Case(  
                                                          Id=att.ParentId,  
                                                         A__c= att.ID
                                              )  
                           );  
                     //add the Caseid in set to eliminate dupe updates                                     
                  accIds.add(att.ParentId);  
             }  
             
             if(att.ParentId.getSobjectType() == Case.SobjectType && (!accIds.contains(att.ParentId)) && att.Name.contains('ABC')){  
                  //prepare a Case object for update  
                  Cases.add(  
                                      new Case(  
                                                          Id=att.ParentId,  
                                                        X__c = att.ID )
                           );  
                     //add the Caseid in set to eliminate dupe updates                                     
                  accIds.add(att.ParentId);  
             }  
             
        }  
        //finally update Cases  
        update Cases;  
 }