1

I took this code from cookbook but the problem is it's throwing error message when i open and edit the existing record can somebody tell me where i'm going wrong.

if open existing record and give junk email address even then it is throwing the same error message saying duplicate exists.

trigger Duplicate_email on Lead (before insert, before update) {

    map<string, Lead> leadMap = new map<string, Lead>();

    for(Lead lead : system.trigger.new){
        if((lead.Email != null) && (system.Trigger.isInsert || 
            (lead.Email == system.trigger.oldMap.get(lead.id).Email)))
        {
            if(leadmap.ContainsKey(lead.Email)){
                lead.Email.addError('Another new lead has the' + ' same email address');
            } else {
                leadMap.put(lead.Email, Lead);
            }
        }
    }

    for(Lead lead : [SELECT Email FROM Lead WHERE Email IN : leadMap.keySet()]){
        Lead newLead = leadmap.get(lead.Email);
        if(!leadmap.get(lead.Email).allow_dups__c){
            system.debug('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@');
            newLead.Email.addError('A lead with this email address already exists. If you still want to enter a new lead with this email, select the Allow Duplicate checkbox to proceed');
        }
    }    
}
1

Sharat,

your trigger runs on both before insert and before update..

so when you update leadA with emailA, the second for loop is querying all Leads with emailA which includes leadA as well. so effectively it compares the record you are updating with itself and throwing the error..

you can compare the lead ids and see if its not the same lead and then throw the error.. hope the below code will work for you

for(Lead lead : [SELECT Email FROM Lead WHERE Email IN : leadMap.keySet()]){
    Lead newLead = leadmap.get(lead.Email);
    if(!leadmap.get(lead.Email).allow_dups__c && lead.Id != newLead.Id){
         newLead.Email.addError('A lead with this email address already exists. If you still want to enter a new lead with this email, select the Allow Duplicate checkbox to proceed');
    }
0

Actually the problem is with your first if condition as below:

lead.Email == system.trigger.oldMap.get(lead.id).Email)

Instead of this you should use

lead.Email != system.trigger.oldMap.get(lead.id).Email)

as if the email is not updating then you should not enter the email in the leadmap so that the email will not get compared with that email. Hope it solves your problem.

Thanks, Saurabh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.