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
Kon DeleKon Dele 

Updating OpportunityLineItem fields issue

I've written a trigger that updates some fields on the Opportunity Product object with Product values when the Opportunity reaches 95% probability.
The trigger works when I edit and save the OpportunityLineItem but does not update if I just change the Opportunity stage to 95%.
What adjustments do i need to make so that the fields are updated as soon as the Opportunity reaches 95%?
trigger OppProductNetValue on OpportunityLineItem (before insert, before update) {
 
  Map<Id,Opportunity> parentopps = new Map<Id, Opportunity>();

  Set<Id> pbeIds = new Set<Id>();
  
     for(OpportunityLineItem oli : trigger.new) {
        if(oli.PriceBookEntryId != null){
            pbeIds.add(oli.PriceBookEntryId);
            parentopps.put(oli.OpportunityId,null);
       }
    }
    Map<id, PriceBookEntry> pbeMap = new Map<id, PriceBookEntry>(
          [SELECT id, Product2.id, Product2.True_Price__c
         FROM PriceBookEntry WHERE id in :pbeIds]);
    parentopps.putall([select Id, Probability, Order__c from Opportunity where Id in :parentopps.keyset()]);
    
     for(OpportunityLineItem oli : trigger.new) {
        if((pbeMap.containsKey(oli.PriceBookEntryId))&&(parentopps.get(oli.OpportunityId).Order__c == 'Sales Line')&&(parentopps.get(oli.OpportunityId).Probability == 95)){
           oli.Net_Value__c = pbeMap.get(oli.PriceBookEntryId).Product2.True_Price__c*oli.Quantity;      
      }else{
           oli.Net_Value__c = (1-oli.Discount*.01)*(oli.Quantity)*(oli.UnitPrice);
   }  
  }
}

 
Best Answer chosen by Kon Dele
RamuRamu (Salesforce Developers) 
The change you would need to do is change the trigger to Opportunity trigger and tweak the coding. If you notice, the current trigger is written for OpportunityLineItems, hence it is triggering when you make some changes to OpportunityLineItems. If you write a trigger on Opportunity, it will fire when there are any changes done on Opportunities.

Hope this helps !!

All Answers

RamuRamu (Salesforce Developers) 
The change you would need to do is change the trigger to Opportunity trigger and tweak the coding. If you notice, the current trigger is written for OpportunityLineItems, hence it is triggering when you make some changes to OpportunityLineItems. If you write a trigger on Opportunity, it will fire when there are any changes done on Opportunities.

Hope this helps !!
This was selected as the best answer
Kon DeleKon Dele
I tried writing a trigger for Opportunity but I get the compile error: 'Loop must iterate over a collection type: SOBJECT:Opportunity' at the FOR Loop lines. Could you please post an edit example of my trigger so that it compiles on the Opportunity Object?