Is there a resource somewhere that would help me figure out why a trigger I wrote is causing web-based leads to be rejected? I get an email containing each lead when this trigger is running. Or, can someone simply TELL me what is wrong here? "Unexpected exception" isn't very helpful (see below). :-/
This trigger searches for duplicate leads (or accounts if the code is uncommented) and marks how many it found into a couple of fields - essentially a dupe checker (based on email address which is how this company operates) so we can filter them as needed - non-dupes go through, dupes get manhandled.
The code works FINE (though this version is several revisions later) except for rejecting web-based lead insertions from web-forms.
Thanks for any guidance. ;-) Code is below.
trigger emailDuplicateCounter_LEAD on Lead (before insert) {
//trigger emailDuplicateCounter_LEAD on Lead (before insert, before update) {
// ORIGINAL...
// http://www.salesforce.com/docs/developer/cookbook/Content/apex_dedupe.htm
Map<String, Lead> leadMap = new Map<String, Lead>([select id, Email from Lead WHERE Name != '' ]);
// Reset Dupe Email (leads) marker; add email(s) to list of those to check
for (Lead leadLoop : System.Trigger.new) {
// ins 1 + 2
leadMap.put(leadLoop.Email, leadLoop);
}
// Single dbase query, find all leads with same email address as any of the leads being ins
for ( Lead leadLoop2 : [SELECT Email FROM Lead WHERE Email IN :leadMap.KeySet()] ) {
Lead newLead = leadMap.get(leadLoop2.Email);
// ins 3
if (System.Trigger.isInsert) {
newLead.Dupe_Email_in_leads_When_Created__c = true;
}
}
// check Accounts similarly... ** COMMENTED FOR NOW **
// for ( Account account : [SELECT PersonEmail FROM Account WHERE PersonEmail IN :leadMap.KeySet()] ) {
// Lead newLead = leadMap.get(account.PersonEmail);
// ins 4
// if (System.Trigger.isInsert) {
//newLead.Dupe_Email_in_accounts_When_Created__c = true;
// }
}
// code to fix/ insert later with more logic...
// 1 leadLoop.Dupe_Email_in_leads__c = false;
// 2 leadLoop.Dupe_Email_in_Accounts__c = false;
// 3 newLead.Dupe_Email_in_leads__c = true; would need on UPDATE, misfires....
// 4 newLead.Dupe_Email_in_accounts__c = true; similar to above...
}
The error on the emails that contain the non-inserted lead is:
Salesforce could not create this lead because of the reason listed below. For more information about this error or help with Web-to-Case-Lead, please contact Customer Support.
Reason: Apex trigger emailDuplicateCounter_LEAD caused an unexpected exception, contact your administrator: emailDuplicateCounter_LEAD: execution of BeforeInsert
caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.emailDuplicateCounter_LEAD