[SalesForce] Allow Duplicate Email but alert user that this email already exist

This is one weird requirement for our client, they want to allow duplicate email in Lead object, but when saving the record it should alert them saying that "A lead With this email address already exist" I had written trigger to avoid duplicate as shown below please suggest me some solution for this

This is my trigger to avoid duplicate email in lead.

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);
        newLead.Email.addError('A lead with this email address'+' already exist');
    } 
} 

Thank You 🙂

Best Answer

There is no way to have a trigger based "warning" that still allows the user to proceed. One technique you could use would be to add an "Allow Duplicate" checkbox (my code uses the api name of "allow_dups__c", and bypass your adderror when selected. Then, the user would get the error based on your existing code, but the message would be changed to "A lead with this email address already exists. If you still want to enter a new lead with this address, select the Allow Duplicate checkbox to proceed".

Something like this:

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.allow_dups__c)){
        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){
         newLead.Email.addError('A lead with this email address'+' already exist');
    }
} 
} 
Related Topic