Development questions

Write a custom Roll-Up Summary trigger to count the total number of Contacts on an Account (handling Insert, Update, Delete, Undelete, and Account Reparenting).

Handle all events, collect affected Account Ids (including the old AccountId when reparenting), and recompute with an aggregate query.

apex
trigger ContactRollup on Contact (after insert, after update, after delete, after undelete) {
    Set<Id> accIds = new Set<Id>();
    List<Contact> src = Trigger.isDelete ? Trigger.old : Trigger.new;
    for (Contact c : src) {
        if (c.AccountId != null) accIds.add(c.AccountId);
        if (Trigger.isUpdate) {
            Id oldId = Trigger.oldMap.get(c.Id).AccountId;
            if (oldId != null) accIds.add(oldId);
        }
    }
    Map<Id, Integer> counts = new Map<Id, Integer>();
    for (AggregateResult ar : [SELECT AccountId a, COUNT(Id) c FROM Contact
                                WHERE AccountId IN :accIds GROUP BY AccountId]) {
        counts.put((Id) ar.get('a'), (Integer) ar.get('c'));
    }
    List<Account> toUpdate = new List<Account>();
    for (Id id : accIds) {
        toUpdate.add(new Account(Id = id, Contact_Count__c = counts.containsKey(id) ? counts.get(id) : 0));
    }
    update toUpdate;
}

Accounts with no contacts get 0.

apex-triggertriggercodingscenariorollup