Hey guys, today in this post we are going to learn about How to Check Duplicate Email on Lead Object in Salesforce.
Real time scenarios:- Write a trigger on lead to prevent duplicate records based on lead email, if a record already created with the same Email, Or record is Updated. The trigger should throw an error.
Files we used in this post example
duplicateEmailCheckLead.apxt | Apex Class Trigger | It will be fired wheneverΒ New Lead is Created Or Updated |
leadHandlerController.apxc | Apex Class Controller | Apex handler trigger to prevent duplicate records based on lead email. |
Standard Object:-Β Lead | Trigger to prevent duplicate lead based on email. |
Final Output
You can download file directly from github by Click Here.
Other related post that would you like to learn in Salesforce
- Find the below steps for this post.
Create Apex Trigger
Step 1:- Apex Class Trigger : duplicateEmailCheckLead.apxt
From Developer Console β‘ File β‘ New β‘ Apex Trigger
duplicateEmailCheckLead.apxt [Apex Class Trigger]
TRIGGER duplicateEmailCheckOnLead ON Lead (BEFORE INSERT, after INSERT, BEFORE UPDATE, after UPDATE) {
IF(TRIGGER.isBefore){
IF(TRIGGER.isInsert){
leadHandlerController.updateInsertLead(TRIGGER.new);
}
IF(TRIGGER.isUpdate){
leadHandlerController.updateInsertLead(TRIGGER.new);
}
}
ELSE IF(TRIGGER.isAfter){
system.debug('I am inside of after method');
}
}
Create Apex Class Controller
Step 2:- Create Apex Class : leadHandlerController.apxc
From Developer Console β‘ File β‘ New β‘ Apex Class
leadHandlerController.apxc [Apex Class Controller]
public class leadHandlerController {
public static void updateInsertLead(List<Lead> leadObjList){
Set<String> setStr = NEW Set<String>();
List<Lead> leadObj = NEW List<Lead>();
List<Lead> leadList=[SELECT Id, Name, Email, Phone FROM Lead WHERE Email != NULL];
FOR(Lead d1:leadList){
setStr.add(d1.Email);
}
FOR(lead e1:leadObjList){
IF(setStr.contains(e1.Email)){
e1.Email.addError('Do not allow duplicate Email');
}
}
}
}
Further post that would you like to learn in Salesforce
How can you avoid maximum trigger depth exceeded?
To avoid these kind of situation we can use public class static variable. We can solve this issue, you can set a condition on trigger so it will not be called recursively.
Why is my trigger running twice?
Triggers can fire twice, once before workflows and once after workflows.
How many times trigger will fire in Salesforce?
Triggers execute on batches of 200 records at a time. So if 400 records cause a trigger to fire, the trigger fires twice, once for each 200 records.
Related Topics | You May Also Like
Our Free Courses β
π Get Free Course β
π Salesforce Administrators π Salesforce Lightning Flow Builder π Salesforce Record Trigger Flow Builder |
π Get Free Course β
π Aura Lightning Framework π Lightning Web Component (LWC) π Rest APIs Integration |