I have to write a duplication trigger on OpportunityLineItem to perform a duplication check so that the same product can not be added to the Opportunity again.If the same product is added to the opportunity again, it should throw an error on the UI saying that "This product already exist on the opportunity."I have written the code .So far even if a new product is added it still shows an error message.
trigger OpportunityLineItemCheck on OpportunityLineItem (after insert,after update) {
OpportunityLineItemCheckOperations opportunityLineItemCheckOperations=new OpportunityLineItemCheckOperations();
opportunityLineItemCheckOperations.checkOnOpportunityLineItems(trigger.new);
}
public class OpportunityLineItemCheckOperations {
public void checkOnOpportunityLineItems(List<OpportunityLineItem> opportunityProductList){
List<Opportunity> opportunityList=[SELECT ID FROM Opportunity];
system.debug('opportunityList@@@@@'+opportunityList);
OpportunityLineItem opportunityPrductObj=[SELECT ID,OpportunityId FROM OpportunityLineItem WHERE OpportunityId IN:opportunityList ];
system.debug('opportunityPrductObj@@@@@'+opportunityPrductObj);
for(OpportunityLineItem oli:opportunityProductList ){
if (oli.OpportunityId==opportunityPrductObj.OpportunityId) {
oli.addError('Opportunity Product Already Exists');
}
}
}
}