title: Clone an opportunity and its lineitems programatically in salesforce
body: <p>I have a scenario where i need to clone a opportunity and its lineitems when the contract End date is today. The opp line item has field called Product_Family_<em>c. i would have to clone only those opp whose lineitems have renewaltype</em>_c as monthly.
  I am stuck at how i can clone over the oli items and assign the new oppty ids to the oli items.</p>
  
  <pre><code>   todays=date.today();
      system.debug('todays'+todays);      
      for(opportunity o:[select Auto_Renew__c,Contract_lenght_in_months__c,Contract_End_Date__c,id from opportunity where Auto_Renew__c='Yes' and Contract_End_Date__c =:todays ])
      {
          SetOppId.add(o.id);
          MapOpp.put(o.id,o);
      }
      system.debug('SetOppId'+SetOppId);
      system.debug('MapOpp'+MapOpp);
      for(OpportunityLineItem oli:[select OpportunityId from OpportunityLineItem where Product_Family__c='Monthly' and OpportunityId in :SetOppId])
      {
          SetOppIdtoRenew.add(oli.OpportunityId);
          Mapoli.put(oli.id,oli);
  
      }
      system.debug('SetOppIdtoRenew'+SetOppIdtoRenew);
      for(id a:SetOppIdtoRenew)
      {
          //MapOpp.get(a).Contract_End_Date__c=MapOpp.get(a).Contract_End_Date__c.addDays(1);
          //MapOpp.get(a).Contract_End_Date__c=MapOpp.get(a).Contract_End_Date__c.addMonths(integer.valueof(MapOpp.get(a).Contract_lenght_in_months__c));
          Lstopp.add(new opportunity(name=MapOpp.get(a).name+' renewal '+string.valueof(date.today()),
                                   Contract_lenght_in_months__c=MapOpp.get(a).Contract_lenght_in_months__c,
                                   Contract_End_Date__c=MapOpp.get(a).Contract_End_Date__c.addMonths(integer.valueof(MapOpp.get(a).Contract_lenght_in_months__c))+1,
                                   StageName=MapOpp.get(a).StageName,
                                   CloseDate=MapOpp.get(a).CloseDate
                              //   ,&lt;fieldname&gt;=MapOpp.get(a).&lt;fieldname&gt;... for all the fields you ned to copy over
                                   ));
  
      }
      system.debug('Lstopp'+Lstopp);
      insert Lstopp;
  </code></pre>