[SalesForce] Trigger to check duplicate Phone and Email

I've to write trigger on lead object to check duplicate phone and email.

one checkbox field Named Duplicate on lead object.
If duplicate record found , checkbox to be checked.

User may Either enter phone or Email or both

Please help to write trigger

Best Answer

trigger on lead tgrLead(before insert, before update){
    leadHandler leadHan = new leadHandler();
    if(trigger.isInsert && trigger.isBefore){
        leadHan.DuplicateChecker(trigger.new);
    }
}

public class leadHandler{
    set<string> setPhones = new set<string>();
    set<string> setEmails = new set<string>();
    list<Lead> lstLead = new list<Lead>();
    map<string, lead> mapEmailWithLead = new map<string, lead>();
    map<string, lead> mapPhoneWithLead = new map<string, lead>();


    public void DuplicateChecker(List<Lead> lstNewLead){
        for(Lead oLead : lstNewLead){
            if(oLead.Phone != null){
             setPhones.add(oLead.Phone);
            }
            if(oLead.email != null){
             setEmails.add(oLead.email);
            }
        }
        lstLead = [select id, phone, email from lead where phone in :setPhones or email in :setEmails ];
        for(Lead oLead : lstLead){
            if(string.isNotEmpty(oLead.email)){
                mapEmailWithLead.put(oLead.email, oLead);
            }
            if(string.isNotEmpty(oLead.phone)){
                mapPhoneWithLead.put(oLead.phone, oLead);
            }
        }

        for(Lead oLead : lstNewLead){
            if(mapEmailWithLead.containsKey(oLead.email) || mapPhoneWithLead.containsKey(oLead.phone)){
                oLead.duplicate__c = true;
            }
        }


    }

}
Related Topic