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
JonSimmonsJonSimmons 

Trigger.New.Add - Collection is read-only??

The APEX Language Reference and Force.com Developers Guides (among others) state that the New collection can be written to in a Before Insert trigger.   Unfortunately when I try to do so, I get a 'Collection is read-only' error.   What gives?

 

 Sample code:

 

 

trigger ProductKits on OpportunityLineItem (before insert)
{

 

//test, just add an opportunitylineitem to trigger.new
            OpportunityLineItem bLineItem = new OpportunityLineItem();
                    bLineItem.quantity = 1;
                    bLineItem.UnitPrice = 100.00;
                    bLineItem.Opportunityid = '006S0000002pi1Y';
                    bLineItem.pricebookentryid = '01u80000003LOTJAA4';
            trigger.new.add(bLineItem);

 

}

JimRaeJimRae
I believe you might be misunderstanding what the guide is saying.  You can update field values on records that exist in the Trigger.new list, but I can't find any reference that indicates you can add new records while the trigger is firing.  Maybe there is a different way to accomplish your design goals?  Why are you trying to add a record to the collection mid-flight?
ianzepp.ax604ianzepp.ax604

I suspect that what the documentation means by 'can be written to' is that you can modify the objects in the Trigger.new list, not that you can add new objects to the end of the list. For example:

 

trigger ProductKits on OpportunityLineItem (before insert) {

    for (OpportunityLineItem opportunityLineItem : Trigger.new) {

         opportunityLineItem.Quantity = 15; 

         opportunityLineItem.UnitPrice = 10.0;

    }

}

 

Hope that helps.

 

JonSimmonsJonSimmons

Yeah, that makes sense.

 

What I want to do is, given a specific product lineitem on an opportunity, replace that product with a number of other products.  

 

I tried to build a list of new products to add, then use DML insert but was running into a series of errors, so I though I would try some other methods.  

 

 

ShakilShakil

I don't think you can add Opportunity Product Line items in this way,as trying to add item in collection, you can change values of collection.

 

better try in other way which may meet your requirement

 

 

       OpportunityLineItem bLineItem = new OpportunityLineItem();
                    bLineItem.quantity = 1;
                    bLineItem.UnitPrice = 100.00;
                    bLineItem.Opportunityid = '006S0000002pi1Y';
                    bLineItem.pricebookentryid = '01u80000003LOTJAA4';

 

        Insert bLineItem;

 

 

--Shakil Bagwan