# 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.

**Topic:** Development · **Difficulty:** Medium · **Asked at:** Cognizant, Wipro, Tech Mahindra · **Tags:** apex-trigger, trigger, coding, scenario, rollup

Read it on the site: https://www.forcechallenges.com/interview-questions/write-a-trigger-to-concatenate-the-names-of-all-child-contact-records-comma-separated-onto-a-custom-field-all

## Answer

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.

---
Source: ForceChallenges · last updated 2026-10-19
