User Story
As a Salesforce Administrator,
I want to prevent the creation of duplicate Contact records based on last name, email, and phone,
so that the system maintains data integrity and avoids unnecessary duplication of records.
Acceptance Criteria:
- When a user attempts to create a new Contact, the system should check if a record already exists with the same last name, email, and phone number.
- If a matching record is found, the system should prevent the creation of the new Contact and display an appropriate error message.
- The validation should occur before the Contact record is inserted into the system.
Codes
trigger ContactTrigger on Contact (before insert) {
if(trigger.isBefore && trigger.isInsert) {
ContactTriggerHandler.onBeforeInsert(trigger.new);
}
}
public class ContactTriggerHandler {
public static void onBeforeInsert(List<Contact> newContacts) {
Set<String> contactKeys = new Set<String>();
// Build the keys from the new records
for (Contact con : newContacts) {
String key = con.LastName + '_' + con.Email + '_' + con.Phone;
contactKeys.add(key);
}
// Query existing Contacts that match the keys
Map<String, Contact> existingContactsMap = new Map<String, Contact>();
for (Contact con : [
SELECT Id, LastName, Email, Phone
FROM Contact
WHERE LastName IN :newContacts.getFieldValues('LastName') AND
Email IN :newContacts.getFieldValues('Email') AND
Phone IN :newContacts.getFieldValues('Phone')
]) {
String key = con.LastName + '_' + con.Email + '_' + con.Phone;
existingContactsMap.put(key, con);
}
// Validate if any new Contact matches an existing Contact
for (Contact con : newContacts) {
String key = con.LastName + '_' + con.Email + '_' + con.Phone;
if (existingContactsMap.containsKey(key)) {
con.addError('A Contact with the same last name, email, and phone already exists.');
}
}
}
}