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
EllenHEllenH 

Trigger to insert a line item if another, specific line is present

I am writing a trigger to insert an additionlal Line Item if a specific line item is present.  The code is below, but I keep getting errors that "x" field name is not a field on the SObject Opportunity Line Item.

 

Code is listed below...  Thanks for any review, advice and/or recommendations.

 

trigger InsertRigbyForHarcourt on OpportunityLineItem (after insert) {
    for (Integer i=0; i < Trigger.new.size(); i++)
    {
    
    OpportunityLineItem nw = Trigger.new[i];
    Boolean man = false;  
    PricebookEntry pbe = [select p.Product2Id from PricebookEntry p where p.Id = :nw.PricebookEntryId];
    
    if ( pbe.Product2Id == '01t80000002ZQH6')      //*** ID of product to check for
    {
       OppProdList.add (new OpportunityLineItem
            ( Name = 'Kit (68 Book Set)',
            ProductCode = '3232'));
            OpportunityLineItem__c = nw.Id,
            Quantity = 1,
            UnitPrice = nw.UnitPrice));

        insert OpportunityLineItem;
      }
  }     
 }     

 

 

crop1645crop1645

Ellen

 

When inserting an OpportunityLineItem, you can't set ProductCode directly, instead, you set pricebookentryId and SFDC derives the productCode and ListPrice. This can make for some tricky coding as you have to look up the PricebookEntryId for the desired new line item's product.

 

Also -- It is not best practice to hard code IDs into APEX code, instead, use SOQL to search for the PBE you are looking for as your qualifying line item (by searchiing on the ProductCode field within the PBE)