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
Divyansh Verma 10Divyansh Verma 10 

How to use attachment with trigger

Requirement: Account1 has a attachment and I need to tranfer the particular attachment to the Account2 and delete the the Account1. So how can we do this by using trigger?
VinayVinay (Salesforce Developers) 
Hi Divyansh,

It is not possible to re-parent or update an attachment's ParentId field to transfer attachments. The ParentId cannot be updated with Data Loader or other API tools.

To change their association, you will need to re-upload the attachments to recreate them and associate them with the new parent at that time. You can do this individually in the user interface, or you can export existing attachments and use that export to recreate the attachments on desired records.

Review below link which has more information on updating ParentId.
https://help.salesforce.com/articleView?id=000339827&type=1&mode=1

Sample code for cloning attachments from one object to another.
trigger CopyAttachments on CustomObject(after insert)
{
 Attachment[] attList = [select id, name, body from Attachment where ParentId = :Trigger.new[0].Opportunity__c];
 Attachment[] insertAttList = new Attachment[]{};
         for(Attachment a: attList)
         {
         Attachment att = new Attachment(name = a.name, body = a.body, parentid = Trigger.new[0].id);
         insertAttList.add(att);
         }
        if(insertAttList.size() > 0)
       {
            insert insertAttList;
       }
}

Below are few links for your reference.

https://success.salesforce.com/ideaview?id=08730000000BrAVAA0
https://developer.salesforce.com/forums/?id=9060G0000005WIDQA2
https://help.salesforce.com/articleView?id=loader_attachments.htm&type=5

Appexchange:
https://appexchange.salesforce.com/listingDetail?listingId=a0N30000009wgt9EAA

Hope above information was helpful.

Please mark as Best Answer so that it can help others in the future.

Thanks,
Vinay Kumar