Development questions
Write a trigger to prevent duplicate Contacts based on Email and Phone when inserting or updating a Contact.
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
More Development questions
- What is an Apex Trigger in Salesforce and when should you use it over Flows?
- What is the difference between before triggers and after triggers?
- Explain all Trigger context variables (isInsert, isUpdate, isDelete, isUndelete, isBefore, isAfter, isExecuting, size, operationType).
- What is the difference between Trigger.new and Trigger.old?
- In which trigger events are Trigger.new and Trigger.newMap available?
- In which trigger events are Trigger.old and Trigger.oldMap available?