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
beatitbeatit 

How to copy same Opp Line items to New opportunity from Existing Opp

hi 

 

How to copy same Opp Line items to New opportunity from Existing Opp,apart from cloning is there any way to do that...

 

  //copy the Plot - ONLY INCLUDE THE FIELDS YOU WANT TO COPY
             po = [select Id, Name,venture__c,Plot__c from Plot__c where id = :po.id];
             newPO = po.clone(false);
             newPO.venture__c = po.Venture__c; 
             newPO.plot__c = po.plot__c;
             insert newPO;
 
             // set the id of the new po created for testing
               newRecordId = newPO.id;
               
 
             // copy over the Payments - ONLY INCLUDE THE FIELDS YOU WANT TO COPY
             List<payment__c> items = new List<payment__c>();
             for (payment__c pi : [Select p.Id, p.name,p.Payment_Date__c,p.Receipt_Number__c,p.Payment_Amount__c,p.Purpose_of_Payment__c From payment__c p where plot__c = :po.id]) {
                  payment__c newPI = pi.clone(false);
                
                 newPI.plot__c = newPO.plot__c ;
                  newPI.Payment_Date__c =newpi.Payment_Date__c;
                  newPI.Receipt_Number__c= newpi.Receipt_Number__c;
                  items.add(newPI);
                  delete pi;
                  
             }
             insert items;
             
 

 

 

here i am using the above functonality to clone to new record,with new id....But i want to select the record from Exixting Data base table of Opprtunities

 

Any ideas!?

 

 

crop1645crop1645

beatit --

 

Your approach is sound; just replace Plot_c with Opportunity and Payment__c with OpportunityLineItem

 

You can make a couple of optimizations:

 

1. You only need one Select - Select id, name, amount, closeDate , (select id, quantity, unitPrice from OpportunityLineItems) from Opportunity where ....

 

This gets the source Opportunity and all its line items in one SOQL call

 

2. If you intend on deleting the source OpportunityLineItems as in your code snippet for variable 'pi', then you should build a Set of all source OpportunityLineItem ids and delete in one DML call.

 

You should also wrap with try-catch as validation rules will fire (or other triggers)