The above functionality can be achieved by duplicate rules. But as we are into coding we will be writing trigger for it.
We will be writing Trigger and Handler for it. The best practice for writing a trigger and Calling the apex class in which we will be writing the business logic for it.
Apex Trigger :
trigger on lead tgrLead(before insert, before update){
LeadHandler objLead = new LeadHandler();
if(trigger.isInsert && trigger.isBefore){
objLead.DuplicateCheckerForLead(trigger.new);
}
}
Apex Class For the Above Trigger :
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 DuplicateCheckerForLead(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;
}
}
}
}