Restrict Duplicate Products in Opportunity

Telegram logo Join our Telegram Channel


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 });
        }   
    }
}

3 comments:
  1. Have anyone tried this scenario?
    it is blocking me to save each record on opportunity product.

    ReplyDelete
    Replies
    1. Hi Jayashree, I have tried it, what error are you facing here?

      Delete
    2. Actually 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

Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at rahul@forcetrails.com