0

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

0

1 Answer 1

0
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;
            }
        }


    }

}
2
  • Hi, when Email is provided then it correctly work, but when only phone is provided then it does not check the duplicate field checkbox. actually I tried code for the same, before ask question on stack exchange but i facing same problem in all, due to this i ask this question on stackexchange
    – user29314
    Apr 5, 2016 at 4:44
  • I had used Workflow+field update on Phone field .
    – user29314
    Apr 5, 2016 at 13:16

Not the answer you're looking for? Browse other questions tagged .