+ Start a Discussion
Sitanshu TripathiSitanshu Tripathi 

How to insert the Opportunity Attachment in to the Account Object.

Hi All,

I want insert the same attachment of the Opportunity object to the Account object.
When I query to the attachment object and get the body of that file then I'm not able to convert the "Blob" format of that body.

Please give the correct tested solution (snippet code).

Thanks in Advance.
Hi Sitanshu, few things to consider -- 

1) Based on the standard behavior of Salesforce, when you insert/upload an attachment under an opportunity record, the same attachment shows up under the parent Account as well. This probably solves your query.

2) Now, let's say even if you didn't had Account and an Opportunity objects to begin with (and let's say you have a custom object with look up relationships where you want the same functionality), I would still not query the body of an attachment but rather just clone an attachment and assign it to the new parentId (which is a parent Id of your child object).

Hope it helps!
Sitanshu TripathiSitanshu Tripathi
Hi Harshil,

I agree with your thought but I don't want to clone. I want to read the blob body, convert that in their read format and want to insert under the any of the object. Because the situation is that the 3rd party want to use the Salesforce attachment inside their environment.

Thanks for your given valuable time for my question.
Deepali KulshresthaDeepali Kulshrestha

Hi Sitanshu,

When an attachment is created in opportunity object it by default get created in the account associated to that opportunity.
If you want to create it by code use the below code:

Trigger CopyOpportunityAttachments  on Attachment (after insert)     
    set<id> oppids=new set<id>();
    for(attachment an:trigger.new)
        if(an.ParentId.getSobjectType() == Opportunity.SobjectType)  
    list<Opportunity> oppList =new list<Opportunity>([Select Account.id,Account.name 
                                                        from Opportunity where Id In:oppids]);    
    list<attachment> accatt=new list<attachment>();
    for(Opportunity op:oppList){
        for (attachment am :[select id, name,parentId, body from Attachment where  ParentId in :oppids])                           
            Attachment newFile = New Attachment(Name = am.name, body = 
        insert accatt;}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks and Regards,
Deepali Kulshrestha