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 

Populate OppLineItem field based on Opportunity Stagename Change

I'm trying to write a trigger that would populate a custom field on the OppLineItem when the parent Opportunity stage is updated.

The field would be populated with a value from the Product.

What adjustments do i need to make to my code to get it to function?
trigger OppProductNetValue on Opportunity(before insert,before update){

   Set<Id> pbeIds=new Set<Id>();
   for(OpportunityLineItem oli:opps.OpportunityLineItems){
     if(oli.PricebookEntryId != null){
   Map<Id,Opportunity> oppMap=new Map<Id,Opportunity>(
     [SELECT StageName,Order__c from Opportunity where id in :pbeIds]); 
   Map<id,PriceBookEntry> pbeMap = new Map<id, PriceBookEntry>(
             [SELECT id,, Product2.True_Price__c
                     FROM PriceBookEntry WHERE id in :pbeIds]);
                     oppMap.putall([select Id, StageName, Order__c from Opportunity where Id in:oppMap.keyset()]);
   for(OpportunityLineItem ol:opptys.OpportunityLineItems){
     if((pbeMap.containsKey(oli.PriceBookEntryId))&& (oppMap.get(oli.OpportunityId).Order__c == 'Sales Unit')&&  (oppMap.get(oli.OpportunityId).StageName == 'Won')){
                   oli.Net_Price__c = pbeMap.get(oli.PriceBookEntryId).Product2.True_Price__c*oli.Quantity;      
              oli.Net_Price__c = (1-oli.Discount*.01)*(oli.Quantity)*(oli.UnitPrice);

Shashikant SharmaShashikant Sharma
Please see follwoing steps you need to take to make it work :
First change the event to after update, that is the applicable event.

1. for(OpportunityLineItem oli:opps.OpportunityLineItems){

In this statement you are accessing child records directly, you have to query itOpportunityLineItems as you can not access child records directly from trigger context instance of a record.

2. I see issue in this 
Map<Id,Opportunity> oppMap=new Map<Id,Opportunity>( [SELECT StageName,Order__c from Opportunity where id in :pbeIds]);

You are queriying opportuity and Ids that compared are of PBE 


You trigger flow should be :

1. Trigger will only work on after update , right now events are wrong
2. Get ids of all opp where StageName is changed
3. Query Oppline items for these opportunity
4. Query PBE
Now you have all information needed.
5. Loop over and populate values accordingly