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:
- Prevent the insertion of an Opportunity Product if the controlling product not exist on this Opportunity.
- 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)