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
travis.truetttravis.truett 

Error: cannot specify Id in an insert call

I'm getting the following error from my trigger that duplicates opportunities when we close them:

Error:Apex trigger Create_followup caused an unexpected exception, contact your administrator: Create_followup: execution of BeforeUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, editSchedule: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0 with id 00oK0000000UInZIAW; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id] Trigger.editSchedule: line 144, column 1: []: Trigger.Create_followup: line 80, column 1

Essentially, I have a trigger that's duplicating the closed opp and adding the products from the old opp over to the new one. This is the section of the code that's throwing the error:

          List<OpportunityLineItem> oliList = [SELECT OpportunityId, PricebookEntryId, UnitPrice, Quantity, Duration__c, Payment_Terms__c, Discount FROM OpportunityLineItem WHERE OpportunityId IN :Trigger.New];
          List<OpportunityLineItem> newoliList = new List<OpportunityLineItem>();
          
          if(!oliList.isEmpty()) {
                Map<Id, Id> oldOpNewOpIdMap2 = new Map<Id, Id>();
               for(Opportunity opNew : listOppor) {
                    oldOpNewOpIdMap2.put(opNew.Parent_Opportunity__c, opNew.Id);
                }   
                
                for(OpportunityLineItem oli : oliList) {
                    
                    OpportunityLineItem newOli = new OpportunityLineItem();
                    newOli.UnitPrice = oli.UnitPrice;
                    
                    newOli.PricebookEntryId = oli.PricebookEntryId;
                    newOli.Quantity = oli.Quantity;
                    newOli.Duration__c = 12;
                   
                    newOli.Payment_Terms__c = oli.Payment_Terms__c;
                    newOli.Discount = oli.Discount;
                    
                    newOli.OpportunityId = oldOpNewOpIdMap2.get(oli.OpportunityId);
                    
                    
                    newoliList.add(newOli);
                }
                
                insert newoliList;

I'm having trouble figuring out why this is happenning and I really need to fix it. Thanks in advance for your help!
Rahul SharmaRahul Sharma
Can you post your complete code.