Free computer code on screen

Custom Roll-up Summary on Account Object | Salesforce Developer Guide

In this article, I’ll demonstrate how to showcase a custom roll-up summary on the Account object.

Before delving into the code, start by creating a custom field of number type on the Account object.

Associated_Contact_Count__c

Our objective is to display the count of all contacts associated with a specific account within the field named “Associated_Contact_Count__c”. This functionality should encompass various events like insertions, updates, deletions, and undeletions.

To achieve this, we’ve developed a trigger on the Contact object, incorporating context variables. However, this implementation is now surpassing the governor limits.

Retrieve all Accounts along with their associated contacts using the query:

Query = [SELECT Id, Associated_Contact_Count__c, (SELECT Id FROM Contacts) FROM Account]

Below is the code that flawlessly implements the same concept across all events.

Code:

trigger customRollupTrigger on Contact (after insert, after update, after delete, after undelete) {         
    Set<Id> accountIds = new Set<Id>();
    system.debug('newData'+ trigger.old);
    if(trigger.isInsert || trigger.isUpdate || trigger.isUndelete){
        system.debug('test1++'+trigger.new);
        for(Contact con:trigger.new){
            if(con.AccountId != null){
                accountIds.add(con.AccountId);
            }
        }
    }
    if(trigger.isAfter && (trigger.isUpdate || trigger.isDelete)){
        system.debug('test2++'+trigger.old);
        for(Contact con:trigger.old){
            if(con.AccountId != null){
                accountIds.add(con.AccountId);
            }
        }
    }
    if(!accountIds.isEmpty()){
        List<Account> accList = new List<Account>();
        for(Account acc:[SELECT Id, Associated_Contact_Count__c, (SELECT Id FROM Contacts) FROM Account WHERE Id IN : accountIds]) {
            acc.Associated_Contact_Count__c=acc.contacts.size();
            accList.add(acc);
            system.debug(acc.Associated_Contact_Count__c);
        }
        update accList;
    }
}