Deep Clone (Parent -> Child -> Grand Child)

I have a requirement to deep clone (Parent -> Child -> Grand Child) records by clicking a button at the Parent Level. I believe Salesforce supports only Clone at the Parent Level, it does not have Deep Clone Out Of the Box. Has anyone ever built it ?

Answer

You could leverage the power of External Ids to join up the objects and use the sObject Clone Method. External Ids let you dynamically match the records, without having to explicitly set the ids of the parent records being created in the clone.

Let’s take the example of Account -> Opportunity -> Opportunity Product

List<Account> accts = new List<Account>{};
List<Opportunity> opptys = new List<Opportunity>{};
List<OpportunityLineItem> olis = new List<OpportunityLineItem>{};

Account acc = [Select Id, Name .... from Account];

Account accNew = acc.clone(false, true); //See sObject Clone Method
accNew.ExternalId__c = acc.Name + Datetime.now(); // set unique external Id
accts.add(accNew);

for(Opportunity opp : [Select Id, Name, ... (Select Id, ... from OpportunityLineItems) from Opportunity where AccountId = :acc.Id]){
Opportunity newOpp = opp.clone(false, true);
newOpp.ExternalId__c = opp.Name + Datetime.now(); //set unique external id

newOpp.Account = new Account(ExternalId__c = accNew.ExternalId__c); //set parent ref

opptys.add(newOpp);

for(OpportunityLineItem oli : opp.OpportunityLineItems){

OpportunityLineItem oliNew = oli.clone(false, true);
oliNew.Opportunity = new Opportunity(ExternalId__c = newOpp.ExternalId__c); //set parent

olis.add(oliNew);
}
}
}
}

insert accts;
upsert opptys; //upsert matches to accounts using external id
upsert olis; //upsert matches to opportunities using external id

Attribution
Source : Link , Question Author : sHiBuKaLiDhAsAn , Answer Author : techtrekker

Leave a Comment