+ Start a Discussion
Lukasz PiziakLukasz Piziak 

Clone record with Sub-records (same record different level)

Hi All,

Can anyone let me know how to clone record (level 1) with sub records (level 2) where records from level 2 are assigned to record level 1.

Many thanks for any help
ANUTEJANUTEJ (Salesforce Developers) 
Hi Lukasz,

I found the below code that could help writing code that clones records, can you try checking them out:

>> https://developer.salesforce.com/forums/?id=9060G000000UZsiQAG

Here is the code that is mentioned in one of the links for quick reference:
class AccountDeepCloneUtil 
    public static void cloneAccount(Account acc) 
        Map<Opportunity,List<OpportunityLineItems>> OpportunityLineItemsMapping = new Map<Opportunity,List<OpportunityLineItems>>();
        List<Opportunity> newOpportunityList = new List<Opportunity>();
        List<Opportunity> oppList = [Select Id, Name, ... (Select Id, ... from OpportunityLineItems) from Opportunity where AccountId = :acc.Id];
        Account newAcc = acc.clone(false, true); //do a deep clone
        //insert the account record
        insert newAcc;
        for(Opportunity opp : oppList){
            Opportunity newOpp = opp.clone(false, true); //do a deep clone
            newOpp.Account = newAcc.Id;
        //insert opportunity
        insert newOpportunityList;

        for(Opportunity opp :OpportunityLineItemsMapping.keySet()){
            for(OpportunityLineItemoppLineItem : OpportunityLineItemsMapping.get(opp)){
                OpportunityLineItem.OpportunityId = opp.Id;

        insert OpportunityLineItemsMapping.values();
Here he is cloning the account and respective child records.

I hope this helps and in case if this comes handy can you please choose this as best answer so that it can be used by others in the future.