[SalesForce] trigger to check duplicate on phone

I write the trigger to check duplicate phone on lead object;
Code as:

trigger DPhone on lead(before insert,before update) 
{
List<Lead> Leadlist =new list<Lead>();
    for(lead l:trigger.new) 

{
    If(l.Phone!=null) 
    Leadlist = [select id from Lead where Phone=:l.Phone];
    If (Leadlist.size()>0)
    l.Phone.adderror('Another record has same Phone No.');
} 
    }

When I create the record its work fine for me . but when i edit the same record and make change in any field, trigger again fire and give me error duplicate phone.

Best Answer

There are two issues with your code.

  1. You have SOQL inside for loop which is not a good practice.
  2. It is throwing error on update for other field as well because you are not checking update of phone field only so solution for that problem is we will check phone field explicitly from Trigger.oldmap (it contains previous value)

    trigger DPhone on lead(before insert,before update) 
    {
    
     //Preparing Lead phone in Set from trigger.new
    
     Set<String> leadSet = new Set<String>();
    
     for(Lead l : trigger.new){
    
         leadSet.add(l.phone);        
     }
    
     //query all existing record for item
     List<Lead> leadList = [select id from lead where phone in : leadSet];
    
    for(lead l:trigger.new) 
    {
        //incase of update
        if(Trigger.isUpdate && l.phone!=null && leadList.size()>0 && Trigger.oldmap.get(l.id).phone!=l.phone)
        {
           l.Phone.adderror('Another record has same Phone No.');
        }
    
        //Because old map is not available we only check for size
        if(Trigger.isInsert && l.phone!=null && leadList.size()>0)
        {
           l.Phone.adderror('Another record has same Phone No.');
        }
    
    } 
    
    }
    
Related Topic