Development questions
Write a trigger to concatenate the names of all child Contact records (comma-separated) onto a custom field All_Contact_Names__c on the parent Account.
Use triggers on Contact (after insert, update, delete, undelete) and rebuild the string for each affected Account from all its Contacts.
apex
trigger ContactTrigger on Contact (after insert, after update, after delete, after undelete) {
Set<Id> accIds = new Set<Id>();
for (Contact c : (Trigger.isDelete ? Trigger.old : Trigger.new)) if (c.AccountId != null) accIds.add(c.AccountId);
if (Trigger.isUpdate) for (Contact c : Trigger.old) if (c.AccountId != null) accIds.add(c.AccountId);
Map<Id, List<String>> names = new Map<Id, List<String>>();
for (Id id : accIds) names.put(id, new List<String>());
for (Contact c : [SELECT AccountId, Name FROM Contact WHERE AccountId IN :accIds ORDER BY Name]) names.get(c.AccountId).add(c.Name);
List<Account> accs = new List<Account>();
for (Id id : accIds) accs.add(new Account(Id = id, All_Contact_Names__c = String.join(names.get(id), ', ')));
update accs;
}
Make sure the field length (e.g. Long Text Area) can hold the data.
apex-triggertriggercodingscenariorollup
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?