I have a Custom Object(Product_Dependency__c) to define dependency between 2 Products with 2 lookup fields to Product. The first lookup is the Controlling product and the second is the dependent product.

The trigger is before insert on Opportunity Products and have 2 goals:

  1. Prevent the insertion of an Opportunity Product if the controlling product not exist on this Opportunity.
  2. Automatically create Opportunity Products of all dependent products if I add their controlling product

For example if I have 2 products A and B. With dependency : A => B (controlling product :A ,dependent product:B)

If I want to add product B on the Opportunity but Product A is not already added or in the same DML opp insert, I will get an Error. If I add the product A , the product B will be added automatically.

First, I would like to know if there is a better way to do that than a trigger and a Custom Object.

Second, my problem in the trigger is like that:

with the same Product A and B (A=>B)

The flow is :

  • I add the product A on the Opp
  • The trigger is called before the insert
  • Check if I can insert A (A don't have controllers : OK)
  • Check if there is dependent products that I need to insert automatically
  • Insert B
  • The trigger is called before the insert
  • Check if I can insert B (I don't find the controller Product because it is neither already on the Opp nor in the same list of Opportunity products that I insert)

So the Product B is not added For now my solution is to use static boolean variable that will check if the trigger is in the first call, if not I don't check for controllers.

But there is 2 problems with that: it is not allowed the case where the product B have an other controller which is missing. it will not work if i add more that 200 Opportunity Products( the trigger will handle per batch of 200 and from the 2nd batch it will not check controllers at all)

1 Answer 1


You should add the dependent records during the "after insert" trigger phase, not "before insert". This allows you to query the database to see if the controllers are already added, and eliminates the need for the static variable to see if the trigger has already run once. And yes, a trigger is probably the most appropriate way to do this type of logic. It is very challenging to do this in a flow, so the trigger is appropriate here.

  • thanks for your answer. So for on Opportunity Product it will call the trigger 2 times ? once before insert to check if i can add this product and once after insert to check if i need to add dependent product ?
    – Raphael D
    Commented Aug 28, 2020 at 14:09
  • @RaphaelD Sure, that should work fine.
    – sfdcfox
    Commented Aug 28, 2020 at 14:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .