The problem I am facing is that the DML operation is being executed and a record Id is generated for the newly inserted record but when I try to query the record or access it in Salesforce, it does not exist. I think the usage of AddError is causing this problem. How should I solve this problem?
trigger duplicateLeadHandler on Lead (before insert) {
List <String> nationalIdList = new List<String>(); //list of all national ids
List<Invalid_Lead__c> invalids = new List<Invalid_Lead__c>(); //list of invalid leads to be inserted
for (Lead ld:trigger.new) {
nationalIdList.add(ld.National_ID__c); //adds all national ids from new leads to be inserted
}
List <Lead> leadList = new List<Lead>();
leadList = [SELECT National_ID__c FROM Lead WHERE National_ID__c in :nationalIdList]; //fetch duplicate national ids from existing leads
for (Lead ld:trigger.new) { //compare for duplicates
If (leadList.size() > 0) {
// Displaying the error on field
ld.National_ID__c.addError( 'Lead already exists. Added to Invalid Leads.' );
//I think addError is the problem since it seems to block DML operations
Invalid_Lead__c invalid = new Invalid_Lead__c ();
System.debug('Create invalid lead');
System.debug('lead national id: ' + ld.National_ID__c);
System.debug('lead phone: ' + ld.Phone);
System.debug('lead email: ' + ld.Email);
invalid.National_ID__c = ld.National_ID__c;
invalid.Phone__c = ld.Phone;
invalid.Email__c = ld.Email;
invalids.add(invalid);
System.debug('invalid lead details: ' + invalid);
System.debug('Added to list');
}
}
try {
insert invalids; //this statement isn't inserting records into Salesforce but it does execute
System.debug('Invalid leads inserted');
}
catch (Exception Ex){
system.debug('Insertion failed: ' + Ex);
}
}