User Story
As a Salesforce developer, I want to create a trigger on Contact object so that duplicate records based on Contact Email, First Name, Last Name, and Phone can be prevented. The trigger will fire on Contact insertion and update and check for existing Contact records with the same email, first name, last name, and phone. If a matching Contact record is found, the trigger will add an error message to prevent the Contact record from being inserted or updated. This will ensure data accuracy and prevent duplicate records in the Contact object.
Code
Apex Trigger
trigger ContactTrigger on Contact ( before insert, before update) {
DuplicateContact.checkDuplicate(Trigger.new);
}
Apex Handler Class
public class DuplicateContact {
public static void checkDuplicate(List<Contact> newContacts){
List<Contact> conList = [SELECT id, FirstName, LastName, Email, Phone from Contact Where FirstName != null AND LastName != null AND Email != null AND Phone != null];
for(Contact conOld : conList){
for(Contact conNew: newContacts){
if(conOld.FirstName == conNew.FirstName && conOld.LastName == conNew.LastName && conOld.Email == conNew.Email && conOld.Phone == conNew.Phone){
conNew.addError('Duplicate contact found...');
break;
}
}
}
}
}
Test Class
@isTest
public class DuplicateContactTest {
@Testsetup
public static void TestSetup(){
Contact con = new Contact(LastName='John', FirstName='John', Email='JohnDoe@demo.com', Phone='4441');
insert con;
}
@isTest
public static void TestA(){
Contact con = new Contact(LastName='John', FirstName='John', Email='JohnDoe@demo.com', Phone='4441');
try{
insert con;
}
catch (DmlException e){
System.assert(e.getMessage().contains('Duplicate contact found...'),'Error message not displayed correctly.');
}
}
}
Video
Video does not exists.