I read through some of the existing posts on here about this error and I think I'm still confused on how to solve it in my context.
I am trying to prevent duplicate products from being added to an opportunity record. I am using the product Id as means to check, which may be an issue in itself between sandbox and production, but for now that is what I went with.
I am getting this error: "sObject row does not allow errors". I am not operating on old records (trigger.old).
My goal is to display a visual error message on the add product screen letting the user know they can't add 2 products with the same product Id
Question: What syntax do I need to modify to avoid this error?
Trigger code below:
trigger OpportunityProductTrigger on OpportunityLineItem (before insert, after insert, before update, after update) {
List<OpportunityLineItem> oppProductList = new List<OpportunityLineItem>();
// insert context
if(Trigger.isInsert) {
if(Trigger.isBefore) {
for (OpportunityLineItem ol : Trigger.New) {
oppProductList.add(ol);
}
OpportunityProductAction.checkDuplicateProducts(oppProductList);
} // close isAfter
}
Class method that gets called from the trigger code:
public static void checkDuplicateProducts(List<OpportunityLineItem> oppProductList) {
Set<Id> oppIds = new Set<Id>();
Set<Id> newProductIds = new Set<Id>();
// get the opportunity ids and product codes passed in
for(OpportunityLineItem ol : oppProductList) {
oppIds.add(ol.OpportunityId);
newProductIds.add(ol.Product2Id);
}
List<OpportunityLineItem> existingProducts = [SELECT Id, Name, ProductCode, Product2Id FROM OpportunityLineItem WHERE OpportunityId IN : OppIds];
for( OpportunityLineItem ol : existingProducts) {
if( newProductIds.contains(ol.Product2Id) ) {
ol.addError('You cannot add duplicate products');
}
}
}