Write a trigger to prevent duplicate Contacts based on Email and Phone when inserting or updating a Contact.
Answer
Use before insert, before update. Compare against existing Contacts in the database and within the same batch.
apex
trigger ContactTrigger on Contact (before insert, before update) {
Set<String> emails = new Set<String>(), phones = new Set<String>();
for (Contact c : Trigger.new) {
if (c.Email != null) emails.add(c.Email);
if (c.Phone != null) phones.add(c.Phone);
}
Set<String> seen = new Set<String>();
for (Contact e : [SELECT Id, Email, Phone FROM Contact
WHERE (Email IN :emails OR Phone IN :phones) AND Id NOT IN :Trigger.new]) {
seen.add(e.Email + '|' + e.Phone);
}
for (Contact c : Trigger.new) {
String key = c.Email + '|' + c.Phone;
if (!seen.add(key)) c.addError('Duplicate Contact with same Email and Phone.');
}
}
In production, prefer Duplicate/Matching Rules where possible.
apex-triggertriggercodingscenarioduplicates