I am simply trying to do as title says. I had a solution originally that worked in only a batch of 1 but as this job is triggered by a TBF and sometimes works in batches it didn't correctly map the ParentId across and cloned every attachment into every custom object in the job.
I am trying to copy the solution from this post: Copying attachments from object to object trigger
However it clones the attachment to the original object not the newly inserted one.
public static void createRiskCheck(Risk_Check__c[] riskcheckcreate){
Schema.DescribeSObjectResult d = Schema.SObjectType.Risk_Check__c;
rtMapByName = d.getRecordTypeInfosByName();
rtRiskCheck = rtMapByName.get('Risk Check');
rtInitialRiskCheck = rtMapByName.get('Initial Risk Check Creation');
Risk_Check__c newriskcheck;
List<Attachment> newattclist = new list<Attachment>();
list<Attachment> attachlist = new list<Attachment>();
list<Note> notelist = new list<Note>();
list<Note> newntelist = new list<Note>();
Set<Id> initialId = new Set<Id>();
List<Risk_Check__c> newriskchecklist = new list<Risk_Check__c>();
for(Risk_Check__c initialcreate : riskcheckcreate){
initialId.add(initialcreate.id);
newriskcheck = new Risk_Check__c();
newriskcheck.Name = initialcreate.Name;
newriskcheck.Reason_for_check__c = initialcreate.Reason_for_check__c;
newriskcheck.Check_Due_Date__c = initialcreate.Next_Review_Date__c;
newriskcheck.Client_Name__c = initialcreate.Client_Name__c;
newriskcheck.member_number_new__c = initialcreate.member_number_new__c;
newriskcheck.Superfund__c = initialcreate.Superfund__c;
newriskcheck.Initial_Risk_Check_Creation__c = initialcreate.Id;
newriskcheck.Related_Account__c = initialcreate.Related_Account__c;
newriskcheck.Stage__c = 'To Be Assigned';
newriskcheck.RecordTypeId = rtRiskCheck.getRecordTypeId();
newriskchecklist.add(newriskcheck);
}
//need to insert the new risk check first so we can use the Id when cloning any attachments on the initial create object
insert newriskchecklist;
attachlist = [select Id, SystemModstamp, ParentId, OwnerId, Name, LastModifiedDate, LastModifiedById, IsPrivate,
IsDeleted, Description, CreatedDate, CreatedById, ContentType, BodyLength, Body from Attachment where ParentId in: initialId];
if(initialId != null && initialId.size() > 0){
Map<Id,Risk_Check__c> riskcheckMap = new Map<Id,Risk_Check__c>([select Id,Initial_Risk_Check_Creation__c
from Risk_Check__c where Initial_Risk_Check_Creation__c in : initialId]);
List<Attachment> attachments = new List<Attachment>();
for(Attachment file : attachlist){
Attachment newFile = file.clone();
if(riskcheckMap.containsKey(file.ParentId) && riskcheckMap.get(file.ParentId).Id != null){
newFile.ParentId = riskcheckMap.get(file.ParentId).Id;
}
attachments.add(newFile);
}
insert attachments;
}
}
file.ParentId= riskcheckMap.get(file.ParentId).Id
. SO which parent you want to assign the Id.