You need to sign in to do that
Don't have an account?
Emily Phillips
addError Method prevents other records from being inserted
Hello, I'm using a trigger (before insert) and trigger handler to check for duplicates on a custom object. There can only be 1 custom object record with the Status of 'Open' per Opportunity Line Item. I've used the addError method to display an error to the user if they try to add another custom object record with the status of 'Open'. The trigger works great if I'm inserting just 1 record and my error message displays correctly. However, if I insert a list of records through the Execute Anonymous window where 1 record meets the error condition and other records are valid, none of the records are inserted. I understand the addError method stops the operation but I'm not sure how to insert the valid records while preventing the duplicate. Any help is appreciated!
Test code: public class DuplicateTriggerHandler{ public static void checkForDuplicate(List<Custom_Object__c> coList){ Set<Id> oliId = new Set<Id>(); for(Custom_Object__c co : coList){ oliId.add(co.Opportunity_Line_Item__c); System.debug('co.Opportunity_Line_Item__c: ' + co.Opportunity_Line_Item__c); } List< Custom_Object__c > coList2 = [Select Id from Custom_Object__c where Opportunity_Line_Item__c in: oliId and Status__c = 'Open']; System.debug(' coList2:' + coList2); for(Custom_Object__c co : coList){ if(co.Status__c == 'Open' && coList2.size() > 0){ co.addError('Error: You cannot have more than one Custom Object Record with the status of Open.'); } } } }
Are you inserting custom object records for different Opportunity_Line_Item__c records?
If you try to insering the same custom object records for same Opportunity_Line_Item__c record then you will get the error.
Try to modify your code like below.
If this helps, Please mark it as best answer.
Thanks!!