Transfer attachments from one Object to another Object #inSalesforce
Move all related Attachments of Unused Contact to either Opportunity (if linked) or Account record.
List<Contact> contList = new List<Contact>();
//Get the details of Contact where status is Unused and related to Account or Opportunity
contList = [Select Id,Company__c,Opportunity__c from Contact where Status__c = 'Unused' AND (Company__c != NULL OR Opportunity__c != NULL)];
//Get the contact details while iterating over attachment records
Map<Id,Contact> contMap = new Map<Id,Contact>(contList);
//Store all contact IDs, which will be used to get all related attachments
Set<Id> contIds = new Set<Id>();
for(Contact cont : contList){
contIds.add(cont.Id);
}
//Get the attachments of corresponding Contact Object
List<Attachment> allAttchments = new List<Attachment>();
allAttchments = [Select Id,Name,Body,ParentId From Attachment Where ParentId IN :contIds];
//Final List to insert attchment into new destination object
List<Attachment> attachmentsforInsert = new List<Attachment>();
for(Attachment attach : allAttchments){
attach.Id = null;
if(contMap.get(attach.ParentId).Opportunity__c == null){
attach.ParentId = contMap.get(attach.ParentId).Company__c;
}else{
attach.ParentId = contMap.get(attach.ParentId).Opportunity__c;
}
attachmentsforInsert.add(attach);
}
if(!attachmentsforInsert.isEmpty()){
Insert attachmentsforInsert;
}
//Get the details of Contact where status is Unused and related to Account or Opportunity
contList = [Select Id,Company__c,Opportunity__c from Contact where Status__c = 'Unused' AND (Company__c != NULL OR Opportunity__c != NULL)];
//Get the contact details while iterating over attachment records
Map<Id,Contact> contMap = new Map<Id,Contact>(contList);
//Store all contact IDs, which will be used to get all related attachments
Set<Id> contIds = new Set<Id>();
for(Contact cont : contList){
contIds.add(cont.Id);
}
//Get the attachments of corresponding Contact Object
List<Attachment> allAttchments = new List<Attachment>();
allAttchments = [Select Id,Name,Body,ParentId From Attachment Where ParentId IN :contIds];
//Final List to insert attchment into new destination object
List<Attachment> attachmentsforInsert = new List<Attachment>();
for(Attachment attach : allAttchments){
attach.Id = null;
if(contMap.get(attach.ParentId).Opportunity__c == null){
attach.ParentId = contMap.get(attach.ParentId).Company__c;
}else{
attach.ParentId = contMap.get(attach.ParentId).Opportunity__c;
}
attachmentsforInsert.add(attach);
}
if(!attachmentsforInsert.isEmpty()){
Insert attachmentsforInsert;
}
Comments
Post a Comment