Here is the scenario: I have a Bundle product which when added to the opportunity should add related products in that Bundle. I have written trigger on after insert but instead of adding related products from that bundle, it adds the bundle product again that many times. Suppose we have a bundle product 'Bundle1' and related product 'Prod1' and 'Prod2'. Then on inserting Bundle1 it should add 'Prod1' and 'Prod2' also. But it adds 'Bundle1' itself 3 times. The trigger was recursive so I've added Boolean but looks like it was recursive because the same bundle product was getting added again. Can anyone tell what is the issue with the code and how to resolve.
Here is the code:
Trigger:
trigger oppProdTrigger on OpportunityLineItem (after insert) {
if(trigger.isAfter && trigger.isInsert){
if(!OppLineItemHandler.isTriggered){
OppLineItemHandler.createBundleProducts(trigger.new);
}
}
}
Handler Class:
public class OppLineItemHandler {
public static boolean isTriggered = false;
public static void createBundleProducts(List<OpportunityLineItem> newOpptyItems){
List<Product2> lstBundledProducts = new List<Product2>();
//Prod1 and Prod2 Ids ---------
List<Id> lstBundledProdIds = new List<Id>{'01t28000003hbxmAAA','01t28000003hbxfAAA'};
List<OpportunityLineItem> newLineItemLst = new List<OpportunityLineItem>();
for(OpportunityLineItem oppLineItem : newOpptyItems){
for(Id productId : lstBundledProdIds){
System.debug('enter here--3--');
OpportunityLineItem oli = new OpportunityLineItem();
oli.OpportunityId = oppLineItem.OpportunityId;
oli.Product2Id = productId;
oli.Quantity = oppLineItem.Quantity;
oli.UnitPrice = oppLineItem.UnitPrice;
oli.PricebookEntryId = oppLineItem.PricebookEntryId;
newLineItemLst.add(oli);
}
}
try{
if(!newLineItemLst.isEmpty()) {
isTriggered = true;
insert newLineItemLst;
}
}catch(System.DMLException de){
}
}
}