0

I created a trigger that on creation of an OpportunitlyLineItem that looks at the number of OpportunityLineItemSchedule IDs and sets a Duration field (on OpportunityLineItem as the size of the list. This was deployed to production in Nov. 2015 and worked. Now the trigger only fires when the OpportunityLineItem is edited. I can't trace through to figure out what is going on. I tried changing to after insert but it is throwing a System.FinalException: Record is read-only error.

Here is the trigger if someone could please point me in the right direction. Thank you!

trigger NumInstallments on OpportunityLineItem (before insert, before update) {
for(OpportunityLineItem lineItem : Trigger.new){
            List<OpportunityLineItemSchedule> numSched = [Select Id From OpportunityLineItemSchedule
                                                                Where OpportunityLineItemId = :lineItem.Id];
            if (numSched.size() > 0){
                lineItem.Duration__c = numSched.size();
               } else {
                lineItem.Duration__c = null; 
              }
             } 
}
1
  • 1
    Lineitem.id doesn't exist in before insert event Commented Apr 22, 2016 at 15:49

1 Answer 1

1

Ilya is right that the ID you are using doesn't exist at that point. You can find more info about that here: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_context_variables.htm

To answer this question, you need to convert it to an after trigger. As it says in the above link, though, you can't modify it in place. Add the LineItems to a new list and insert that. This isn't ideal though because you can cause all sorts of problems when you re-trigger updates in circles.

The better fix for this exact issue, however, is to make Duration__c a roll up summary that counts the number schedules.

1
  • thanks for the response. A roll-up summary would be the ideal solution (would have saved me some time) but you can't create this field type on Objects where it is not the master (Opportunity is master of OpportunitylineItem.) Is there a work around for this? Commented Apr 22, 2016 at 16:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .