Development questions
When a Lead is created with an Email that already exists on an existing Contact, block the Lead creation or automatically link/merge it.
Use before insert on Lead, query Contacts with matching emails, and either block or link via a custom lookup (e.g. Existing_Contact__c).
apex
trigger LeadTrigger on Lead (before insert) {
Set<String> emails = new Set<String>();
for (Lead l : Trigger.new) if (l.Email != null) emails.add(l.Email);
Map<String, Contact> byEmail = new Map<String, Contact>();
for (Contact c : [SELECT Id, Email FROM Contact WHERE Email IN :emails]) byEmail.put(c.Email, c);
for (Lead l : Trigger.new) {
if (l.Email != null && byEmail.containsKey(l.Email)) {
// Option A: block
l.addError('A Contact with this email already exists.');
// Option B: l.Existing_Contact__c = byEmail.get(l.Email).Id;
}
}
}
Standard Duplicate Rules and Matching Rules can do this across Lead/Contact without code.
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?