function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Avinash@salesforceAvinash@salesforce 

Trigger On Opportunity Product Which Shows an error message

Hi friends,

I am writing a trigger on opportunityLineItem. There is a custom picklist field (ExistingProduct__c) on opportunityLineItem.

Now my scenario is when a opportunityLineItem is added to opportunity with the picklist value as "ExistingProduct__c = YES".

When the user try to add another opportunityLineItem to same opportunity with same picklist value. It should through an error message.
There should be only one opportunity LineItem with ExistingProduct__c ==Yes for one Opportunity.

I tried this way but it's not working.


trigger OpportunityProduct on OpportunityLineItem (before insert) {
    List<Opportunity> opps = [select id,StageName,Ownerid,accountid  from opportunity where id in :opportunityIds];
    List<OpportunityLineItem> opls = [Select Id, ExistingProduct__c from OpportunityLineItem where id in : opportunityIds];
    for(OpportunityLineItem op : trigger.new){
        if(op.ExistingProduct__c == 'Yes'){
           //insert op;
            opportunityLineItem oldopp = trigger.oldMap.get(op.Id);
            if(op.ExistingProduct__c[0] != oldopp.ExistingProduct__c){
                op.addError('*****************');
                
            } 
        }
               
    }
}

 

How to achieve this....?
Could anyone help.
Ajay K DubediAjay K Dubedi
Hi Avinash,
Use this trigger :
 
trigger oplItemWithExistingProduct on OpportunityLineItem (before insert, before update) {  
    Integer i ;
    List<OpportunityLineItem> OplList = new List<OpportunityLineItem>();
    set<Id> setOfOpportunityId = new  set<Id>();
    map<Id,Integer> tempMap = new map<Id,Integer>();
for(OpportunityLineItem opll :Trigger.new){
    setOfOpportunityId.add(opll.OpportunityId);
}
OplList = [SELECT Id,ExistingProduct__c,OpportunityId FROM OpportunityLineItem where OpportunityId In :setOfOpportunityId];
    for(OpportunityLineItem ol:OplList ){
        if(ol.ExistingProduct__c == 'Yes' && tempMap.get(ol.OpportunityId) !=null){
            i++;
               tempMap.put(ol.OpportunityId,i);   
        }
        else{
            i = 1;
            tempMap.put(ol.OpportunityId,i);
        }
    }  
for(OpportunityLineItem opl :trigger.new){   
if(opl.ExistingProduct__c == 'Yes'){
i =tempMap.get(opl.OpportunityId);
    if(i !=null){
i++;
tempMap.put(opl.OpportunityId,i);    
if(tempMap.get(opl.OpportunityId) >=2){   
opl.addError('There should be only one opportunityLineItem with ExistingProduct__c ==Yes for one Opportunity.');
}
}
    else{
        i =1;
        tempMap.put(opl.OpportunityId,i);  
    }
}
}
}
User-added image

Regards,
Ajay