Development questions
If a Contact is marked as Is_Primary__c = true, automatically uncheck Is_Primary__c on all other sibling Contacts under the same Account.
Use after insert, after update, find sibling primaries on the same Accounts (excluding the triggering records), uncheck them, and guard against recursion.
apex
trigger ContactTrigger on Contact (after insert, after update) {
if (ContactHandler.running) return;
Map<Id, Id> primaryByAcc = new Map<Id, Id>();
for (Contact c : Trigger.new) if (c.Is_Primary__c && c.AccountId != null) primaryByAcc.put(c.AccountId, c.Id);
if (primaryByAcc.isEmpty()) return;
List<Contact> sibs = [SELECT Id, AccountId FROM Contact WHERE AccountId IN :primaryByAcc.keySet()
AND Is_Primary__c = true AND Id NOT IN :Trigger.new];
for (Contact s : sibs) s.Is_Primary__c = false;
ContactHandler.running = true;
update sibs;
ContactHandler.running = false;
}
ContactHandler.running is a static Boolean used here only to stop the immediate re-fire.
apex-triggertriggercodingscenariorecursion
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?