function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Vin BVin B 

deep clone with related list hierarchy

I need to clone parent with its related lists which in turn has related lists. i.e parent->child->grand child 

I can clone them using deep clone but i could not avoid soql query inside for loop and also some part of insertion statements. Can anybody help if there is a better way to achieve it?..


code is as shown below...
public class CategoryDeepCloneUtil 
{
    public static void cloneCategoryMaster(Category__c CTM) 
    {
        Map<category_Details__c,List<Category_Detail_Option__c>> OpportunityLineItemsMapping = new Map<category_Details,List<Category_Detail_Option__c>>();
        List<category_Details__c> newOpportunityList = new List<category_Details__c>();
        List<category_Details__c> oppList = [Select Id, Name,Category_Name__c,Category__c,(Select Id,Name,Category_Details__c,Response_Option__c from category_Details__c.Category_Detail_Options__r) from category_Details__c where Category__c= :CTM.Id];
        Category__c newCTM = CTM.clone(false, true); //do a deep clone
        //insert the account record
        insert newCTM;                  
        for(category_Details__c opp : oppList){
            category_Details__c newOpp = opp.clone(false, true); //do a deep clone
            newOpp.Category__c= newCTM .Id;
            newOpportunityList.add(newOpp);
            OpportunityLineItemsMapping.put(newOpp,opp.Category_Detail_Options__r.deepClone(false,false,false));
        }
        //insert opportunity
        insert newOpportunityList;

        for(category_Detailsr__c opp :OpportunityLineItemsMapping.keySet()){
            for(Category_Detail_Option__c oppLineItem : OpportunityLineItemsMapping.get(opp)){
                oppLineItem .Category_Details__c= opp.Id;
            }
        }
           
        insert OpportunityLineItemsMapping.values(); //error showing cannot insert list<list<sobject in dml operation. which forces me to use for loop for accessing map values to insert dem inside for loop. :(
    }
}
 
Ravi Dutt SharmaRavi Dutt Sharma
I have written a blog on this some time back. Have a look, maybe it helps:

http://raviduttsharma.wixsite.com/salesforce/single-post/2016/03/22/Clone-with-Related-list