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
Wenda McMahanWenda McMahan 

Trigger not always returned highest price Opp Line Item

Hi, another newbie programmer here with a question about the following trigger. The intention is to get the Product Abbreviation of only the Product from the highest priced Opportunity Line Item into a field on Opportunity.

The trigger works to get the primary product abbreviation when there is one Opp Line Item, but it is unreliable about getting the highest priced OLI when there is more than one. Any thoughts/help would be very appreciated. Thank you.
 
trigger getProduct on Opportunity (before insert, before update) {
   public list<opportunity> Opps = trigger.new;
   public list<opportunityLineItem> Prods = new list<opportunityLineItem>([SELECT Id, TotalPrice, PricebookEntry.Product2Id, Product2.name,                                                                           PricebookEntry.Product2.Abbreviation__c, opportunityId 
                                            FROM opportunityLineItem WHERE opportunityId =: trigger.new[0].id ORDER BY TotalPrice LIMIT 1]);

  
  string productvar='';
  for(opportunityLineItem p : Prods) {

       productvar = p.PricebookEntry.Product2.Abbreviation__c;

  }

  for(Opportunity opp : trigger.new) {
     opp.Prim_Prod_Abbrev__c = productvar;

  }
}

 
Best Answer chosen by Wenda McMahan
Mathew Andresen 5Mathew Andresen 5
I think if you put a sort order it might work.  
 
ORDER BY TotalPrice DESC LIMIT 1
Also, depending on your data set you might want to add something like != 0 && != NULL
Also, you can test quries in the query editor.  I find that to be very helpful.

All Answers

Mathew Andresen 5Mathew Andresen 5
I think if you put a sort order it might work.  
 
ORDER BY TotalPrice DESC LIMIT 1
Also, depending on your data set you might want to add something like != 0 && != NULL
Also, you can test quries in the query editor.  I find that to be very helpful.
This was selected as the best answer
Wenda McMahanWenda McMahan
Thanks for the response! There is an "ORDER BY" in Line 04. Apparently the "DESC" made the difference. Seems to be working now. Thanks!