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(Opportunity opps:Trigger.new){
for(OpportunityLineItem oli:opps.OpportunityLineItems){
if(oli.PricebookEntryId != null){
pbeIds.add(oli.PricebookEntryId);
}
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.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(Opportunity opptys:Trigger.new){
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;
}else{
oli.Net_Price__c = (1-oli.Discount*.01)*(oli.Quantity)*(oli.UnitPrice);
}
}
}
}
}
}