Development questions
Write a trigger on Contact to ensure a single Account cannot have more than one "Primary Contact" (Is_Primary__c = true).
Use before insert, before update. Count primaries within the incoming batch and against existing primaries in the database.
apex
trigger ContactTrigger on Contact (before insert, before update) {
Set<Id> accIds = new Set<Id>();
for (Contact c : Trigger.new) if (c.Is_Primary__c && c.AccountId != null) accIds.add(c.AccountId);
Set<Id> hasPrimary = new Set<Id>();
for (Contact e : [SELECT AccountId FROM Contact WHERE AccountId IN :accIds
AND Is_Primary__c = true AND Id NOT IN :Trigger.new]) hasPrimary.add(e.AccountId);
for (Contact c : Trigger.new) {
if (c.Is_Primary__c && c.AccountId != null) {
if (!hasPrimary.add(c.AccountId)) c.addError('Account already has a primary Contact.');
}
}
}
Adding to the set also catches duplicates inside the same batch.
apex-triggertriggercodingscenariovalidation
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?