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
Meenakshi T RMeenakshi T R 

Attchments to files

I have a requirement where I have to copy the pdf in Notes and Attachments of Parent object to Files in Child object when it is created. It gets created when the status of the parent object changes to InApproval. My code is

trigger CopyAttachmentsToPIN on Attachment (after insert) {
      Set<Id> bcIds = new Set<Id>();
      for(Attachment file : Trigger.new) 
      {
            // only collect those that are for the InvoiceScan object (others can be ignored)
            if(file.ParentId.getSObjectType() == CTPISA__BookingCapture__c.getSObjectType()) 
            {
                bcIds.add(file.ParentId);
                system.debug(bcIds);
            }
       }
    
    if(!bcIds.isEmpty()) 
    {
                Map<Id,c2g__codaPurchaseInvoice__c> ruMap = new Map<Id,c2g__codaPurchaseInvoice__c>();
                List<Attachment> attachments = new List<Attachment>();
                for(c2g__codaPurchaseInvoice__c obj : [select Id, CTPISA__BookingCapture__c from c2g__codaPurchaseInvoice__c where CTPISA__BookingCapture__c in : bcIds])
                {
                    ruMap.put(obj.CTPISA__BookingCapture__c, obj);
                }
                for(Attachment file : Trigger.new)
                {
                        if(ruMap.containsKey(file.ParentId))
                        {
                            Attachment newFile = file.clone(false);
                            newFile.ParentId = ruMap.get(file.ParentId).Id;
                            attachments.add(newFile);
                        }
                }
        // finally, insert the cloned attachments
        insert attachments;   

    }


}

I need to insert the attachments as Files now it's getting attached as Attachments in Child Object. Any idea?
trigger

 
Rakesh ARakesh A
Hi Meenakshi,
You can try this .. 

https://salesforce.stackexchange.com/questions/234575/adding-attachments-in-apex-convert-the-code-to-add-files
Meenakshi T RMeenakshi T R
Hi Rakesh,

Thank you for the reply. But My doubt after this line 

    insert attachments;  

I will have the attachments in the child objects. Can I add the idea to this code itself or usage of apex class should be there?
 
Rakesh ARakesh A
Hi Meenakshi,

The code I have given is to insert files instead of Attachments. So there wont be 'insert Attachment' statement if you change your code accordingly. If you still want to insert the Attachment and if you are looking for the option to insert Files also. Then you have to leave this code as is and write a trigger on attachment, to Create File for each attachment inserted in the system (Which duplicates the attachment - Not recommended).