Development questions
When a new Contact is inserted without an AccountId, check if an Account exists whose Domain__c matches the Contact's email domain (e.g., @acme.com). If found, link it; if not, create a new Account and link the Contact.
Use before insert on Contact. Extract the email domain, match Account Domain__c, and create missing Accounts in bulk.
apex
trigger ContactTrigger on Contact (before insert) {
Map<String, List<Contact>> byDomain = new Map<String, List<Contact>>();
for (Contact c : Trigger.new) {
if (c.AccountId == null && c.Email != null && c.Email.contains('@')) {
String d = c.Email.substringAfter('@').toLowerCase();
if (!byDomain.containsKey(d)) byDomain.put(d, new List<Contact>());
byDomain.get(d).add(c);
}
}
Map<String, Account> accByDomain = new Map<String, Account>();
for (Account a : [SELECT Id, Domain__c FROM Account WHERE Domain__c IN :byDomain.keySet()]) accByDomain.put(a.Domain__c.toLowerCase(), a);
List<Account> newAccs = new List<Account>();
for (String d : byDomain.keySet()) if (!accByDomain.containsKey(d)) {
Account a = new Account(Name = d, Domain__c = d); accByDomain.put(d, a); newAccs.add(a);
}
insert newAccs;
for (String d : byDomain.keySet()) for (Contact c : byDomain.get(d)) c.AccountId = accByDomain.get(d).Id;
}
apex-triggertriggercodingscenario
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?