Hello Salesforce Developer,
I am sharing trigger code to avoid duplicate products on a particular opportunity.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | trigger RestrictDuplicateProducts on OpportunityLineItem (before insert) { Map<id, Set<Id>> mapOpportunityProducts = new Map<id, Set<Id>>(); Set<Id> oppIdSet = new Set<Id>(); Set<Id> oppLineItemToSkip = new Set<Id>();// skip these items from query for (OpportunityLineItem oppLineItem: Trigger.new) { if(!String.isblank(oppLineItem.id)){ oppLineItemToSkip.add(oppLineItem.id); } oppIdSet.add(oppLineItem.OpportunityId); } system.debug('find me=>'+oppLineItemToSkip); // query all existing line items to check duplicate products List<Opportunity> opps = [Select id, (Select id,Product2Id FROM OpportunityLineItems WHERE id not in : oppLineItemToSkip) FROM Opportunity WHERE Id in : oppIdSet]; for(Opportunity opp : opps){ Set<Id> productIdSet = new Set<Id>(); for(OpportunityLineItem oppLineItem : opp.OpportunityLineItems){ productIdSet.add(oppLineItem.Product2Id); } mapOpportunityProducts.put(opp.Id,productIdSet); } for (OpportunityLineItem oppLineItem: Trigger.new) { if( mapOpportunityProducts.containsKey(oppLineItem.OpportunityId) ) { if(mapOpportunityProducts.get(oppLineItem.OpportunityId).contains(oppLineItem.Product2Id)){ oppLineItem.addError('An Opportunity Line Item already exists.'); } mapOpportunityproducts.get(oppLineItem.OpportunityId).add(oppLineitem.Product2Id); } else{ mapOpportunityProducts.put(oppLineItem.OpportunityId, new Set<Id>{ oppLineItem.Product2Id }); } } } |
Have anyone tried this scenario?
ReplyDeleteit is blocking me to save each record on opportunity product.
Hi Jayashree, I have tried it, what error are you facing here?
DeleteActually just remove "before insert" trigger event and you should be good. trigger need not to be run for update event. so you might want to expose a method and call it only at insert.
Delete