Transfer Files from one object to another object #inSalesforce
Move all related Files of unused Contact to either Opportunity or Account record that is if there's a linked Opportunity, then transfer to Opportunity else to Account.
List<Contact> contactList = new List<Contact>();
//Get all the details of Contact where status is 'Unused' and related to Account or Opportunity
contactList = [Select Id,Company__c,Opportunity__c from Contact where Status__c = 'Unused' AND (Company__c != NULL OR Opportunity__c != NULL)];
//Get contact details while iterating over attachment records
Map<Id,Contact> contactMap = new Map<Id,Contact>(contactList);
//Store all contact IDs, which will be used to get all related attachments
Set<Id> contactIds = new Set<Id>();
for(Contact cont : contactList){
contactIds.add(cont.Id);
}
//Get all related files of corresponding Contact Object
List<ContentDocumentLink> cdlList = new List<ContentDocumentLink> ();
cdlList = [select Id, LinkedEntityId, ContentDocumentId, ShareType, Visibility from ContentDocumentLink where LinkedEntityId IN :contactIds];
//Final List to insert file into target object
list<ContentDocumentLink> cdlListForInsert = new list<ContentDocumentLink> ();
for(ContentDocumentLink cdLink : cdlList){
cdLink.Id = null;
if(contactMap.get(cdLink.LinkedEntityId).Opportunity__c == null){
cdLink.LinkedEntityId = contactMap.get(cdLink.LinkedEntityId).Company__c;
}else{
cdLink.LinkedEntityId = contactMap.get(cdLink.LinkedEntityId).Opportunity__c;
}
cdlListForInsert.add(cdLink);
}
if(!cdlListForInsert.isEmpty()){
database.Insert(cdlListForInsert,false);
}
//Get all the details of Contact where status is 'Unused' and related to Account or Opportunity
contactList = [Select Id,Company__c,Opportunity__c from Contact where Status__c = 'Unused' AND (Company__c != NULL OR Opportunity__c != NULL)];
//Get contact details while iterating over attachment records
Map<Id,Contact> contactMap = new Map<Id,Contact>(contactList);
//Store all contact IDs, which will be used to get all related attachments
Set<Id> contactIds = new Set<Id>();
for(Contact cont : contactList){
contactIds.add(cont.Id);
}
//Get all related files of corresponding Contact Object
List<ContentDocumentLink> cdlList = new List<ContentDocumentLink> ();
cdlList = [select Id, LinkedEntityId, ContentDocumentId, ShareType, Visibility from ContentDocumentLink where LinkedEntityId IN :contactIds];
//Final List to insert file into target object
list<ContentDocumentLink> cdlListForInsert = new list<ContentDocumentLink> ();
for(ContentDocumentLink cdLink : cdlList){
cdLink.Id = null;
if(contactMap.get(cdLink.LinkedEntityId).Opportunity__c == null){
cdLink.LinkedEntityId = contactMap.get(cdLink.LinkedEntityId).Company__c;
}else{
cdLink.LinkedEntityId = contactMap.get(cdLink.LinkedEntityId).Opportunity__c;
}
cdlListForInsert.add(cdLink);
}
if(!cdlListForInsert.isEmpty()){
database.Insert(cdlListForInsert,false);
}
Comments
Post a Comment