+ Start a Discussion

Adding Product X to Opportunities with Y and Z via Apex

I am trying to create Apex code to automatically add Product X to all future opportunities with Products Y and Z? What would be the best way to do this?
This is the code I have so far:

trigger CreateOLI on Opportunity (after insert) {
    List<OpportunityLineItem> oliList = new List<OpportunityLineItem>();

    List<PriceBookEntry> priceBookList = [SELECT Id, Product2Id, Product2.Id, Product2.Name FROM PriceBookEntry WHERE Product2Id='01t1a000000Cwc3' AND PriceBook2.isStandard=true LIMIT 1];

    for (Opportunity oppty: Trigger.new) {
        if (/OLI.Name=Z/) (/OLI.Name=Y) {
            //create new Oli
            OpportunityLineItem oli = new OpportunityLineItem(OpportunityId=oppty.Id, PricebookEntryId=priceBookList[0].Id /*rest of required fields*/);

    insert oliList;
William TranWilliam Tran
Conceptually it looks fine.

You will need to fix the syntax to make it compile and work properly.

Thanks, William. Can you please elaborate on the Syntax piece?
William TranWilliam Tran
The main syntax issue is the IF statement:  

if (/OLI.Name=Z/) (/OLI.Name=Y) 

What are you trying to compare? OLI is not defined yet.

As a common practice, if your question is answered, please choose 1 best answer. 
But you can give every answer a thumb up if that answer is helpful to you. 

Hi William,

Thank you for the response. What I am trying to compare is if an Opportunity has products X and Y in it, to then allow the trigger to happen. How would I be able to do that?
James LoghryJames Loghry
In your current example, you are triggering an the insert of an Opportunity.  This will not work, as the Opportunity needs to exist, before any Opportunity Line Items are added to it, whether they are X, Y, Z or some other product / Opportunity Line Item.  Instead, you will either need to create a Process/Flow on the Opportunity Line Item or a trigger on the Opportunity Line Item, so that it creates "X" when Y or Z OLIs are created, but X does not already exist.  

If you did this from a Process it would look something like this:
  1. Process fires on the Opportunity Line Item object.  The criteria is set to "Product2.Name = Y or Product2.Name = Z"
  2. Fires a Flow, and passes in the OLI as a variable.
  3. The Flow does a fast lookup query for existing "X" OLI.
  4. If the "X" OLI does not exist, then a new OLI is created and associated with the Opportunity and the X product.