0

I have tried deep cloning on the opportunity object which has closed won stages it will also clone the Related Products I have tried cloning the opportunity and it works okay,how will i deep clone it?


 global void execute(Database.BatchableContext BC, List<Opportunity> scope1){

        List<Opportunity> cons = new List<Opportunity>();
        //Opportunity op1 = new Opportunity();
        for(Opportunity p : Scope1){  
              if(p.StageName == 'Closed Won' && p.RecordTypeId == '0122v000000vvSPAAY')
              { 
                 Opportunity opp=new Opportunity();
                        opp = p.clone();
                        insert opp;
              }    

        }  
              //insertAccountsAndContacts(op1);
    }

1 Answer 1

3

There is no native "deep clone" functionality in Apex. Your batch class will need to implement this functionality. In rough outline, it would go like this:

  • Query Opportunities, using subqueries to include desired line items or other child objects.
  • Iterate over query. For each record, clone the Opportunity, and add the clone to a Map<Id, Opportunity> oppMap keyed under the Id of the original Opportunity.
  • After the for loop, do insert oppMap.values().
  • Iterate over the queried Opportunities again. In each iteration of the loop, iterate over each child object, such as Opportunity Line Items. Clone each child record and accumulate a List<OpportunityLineItem>. For each child record, set its parent Opportunity to the clone of its parent by indexing into oppMap with the original parent Id.
  • Outside all loops, insert the lists of child objects.

Your current implementation runs DML in a loop, which you should never do as it squanders limits and will reduce the performance of your batch class by requiring a much lower batch size.

The filters you perform in your execute() method should probably be in the query executed in start() instead.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .