+ Start a Discussion
CBBsfdcCBBsfdc 

Write a trigger to validate duplicates on lead using email when new lead is created

Best Answer chosen by CBBsfdc
SandhyaSandhya (Salesforce Developers) 
Hi,

Below code works.
 
trigger leadDuplicatePreventer on Lead (before insert,after update) {
  list<lead> lead = new   list<lead>(); 
 for(lead a: trigger.new)
 {
lead=[select id,name,email from lead where email=:a.email];
  if(lead.size()>0)
  {
   a.email.adderror('email already exist');
  }
 }
}

Please mark it as solved if my reply was helpful. It will make it available for other as the proper solution.
                                             
Best Regards
Sandhya
 

All Answers

SandhyaSandhya (Salesforce Developers) 
Hi,

Below code works.
 
trigger leadDuplicatePreventer on Lead (before insert,after update) {
  list<lead> lead = new   list<lead>(); 
 for(lead a: trigger.new)
 {
lead=[select id,name,email from lead where email=:a.email];
  if(lead.size()>0)
  {
   a.email.adderror('email already exist');
  }
 }
}

Please mark it as solved if my reply was helpful. It will make it available for other as the proper solution.
                                             
Best Regards
Sandhya
 
This was selected as the best answer
Om PrakashOm Prakash
Hi,
I recommend to complete this trailhead module and you can write this trigger by own.
https://trailhead.salesforce.com/content/learn/modules/apex_triggers

Feel free to ask if any queries in your trigger
 
Vishal_GuptaVishal_Gupta
Hello,

There is no need of trigger for this, you can create a Duplicate Rule and it will work for you. Let me know if you need more help.

User-added image