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
AbAb 

Deep clone of opportunity with related list custom and standard in apex

Hello,
I am trying to do deepclone by below method.
i want to clone opportunity with related list
currentOpp = (Opportunity)stdController.getRecord(); 
Opportunity oppClone = currentOpp.clone(false, true);

but when i do system debug for oppClone, it only contains ID

and i have below error
Error:
insert failed. First exception on row 0 with id 0060Q00000D3AnjQAF; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]
Best Answer chosen by Ab
Santosh Kumar 348Santosh Kumar 348
As you have used below statement:
currentOpp = (Opportunity)stdController.getRecord();
This only returns you the id and when you  are trying to clone the record you are getting the id only.

You need to fetch all the fields which you want to clone, something like mentioned below :
 
currentOpp = (Opportunity)stdController.getRecord();

Opportunity opp =  [Select Id, Name, ... (Select Id, ... from OpportunityLineItems) from Opportunity where id = :currentOpp ]; 
Opportunity newOpp = opp.clone(false, true);

List<OpportunityLineItem > oliList = new List<OpportunityLineItem.(); 
for(OpportunityLineItem oli : opp.OpportunityLineItems){
OpportunityLineItem oliNew = oli.clone(false, true);
oliList .add(oliNew);
}

Do let me know if it helps you and close your query by marking it as solved.