How to transfer attachments from one object to another in Salesforce

Published by

on


Requirement:

Move all related Attachments of deceased Contact to either Opportunity or Account record.

If Opportunity is linked then transfer to Opportunity else to Account.

NOTE: Below code will clone the attachments, so once cloning is completed, you can delete old attachments.

This way you will be safe with backup.

Sample Code:

//Source Object: From which we want to transfer attachments
list<Contact> contactList = new list<Contact>();

//Get all the details of Contact where status is deceased and atleast related to Account or Opportunity
contactList = [Select Id,Company__c,Opportunity__c 
				   from Contact 
				   where Status__c = 'Deceased'
				   AND (Company__c != NULL OR Opportunity__c != NULL)];
			   
//Map to get contact details while iterating over attchment records			   
map<Id,Contact> contactMap= new map<Id,Contact>(contactList);

//Set to store all contact Ids, which will be used to get all related attachments (you can use keyset of above map as well)
set<Id> contactIds = new set<Id>();
for(Contact con : contactList){
    contactIds.add(con.Id);
}

//Get all corresponding attachments of corresponsind Source Object
list<Attachment> allAttchments = new list<Attachment> ();

allAttchments = [Select Id,Name,Body,ParentId 
					From Attachment
					Where ParentId IN :contactIds];

//Final List to insert attchment into new destination object
list<Attachment> allAttchmentsToInsert = new list<Attachment> ();


for(Attachment att : allAttchments){
    att.Id = null;
	//if Opportunity is not linked then transfer to Related Account
    if(contactMap.get(att.ParentId).Opportunity__c == null){        
        att.ParentId = contactMap.get(att.ParentId).Company__c;
    }else{
		//if Opportunity is linked then transfer to related Opportunity
        att.ParentId = contactMap.get(att.ParentId).Opportunity__c;
    }
    allAttchmentsToInsert.add(att);
}

//Copy is ready to clone to new target object
if(!allAttchmentsToInsert.isEmpty()){
    Insert allAttchmentsToInsert;
}