Custom Roll-up Summary

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

In this blog, I would like you to share, how to display a custom roll-up summary on account,

Before moving to code first create a custom field of number type on the Account object. “Associated_Contact_Count__c”. 

Now what we have to do here, we have to show the number of all contacts related to a particular account field named “Associated_Contact_Count__c”.and it works for all events insert, updates, delete and undelete.

We will write a trigger on the Contact object and we have used context variables, and the governor limit is also now exceeding.

dont miss out iconDon't forget to check out: Step By Step to turn On Salesforce Multi-Factor Authentication for Every Login

Fetch all the Account with related contacts by the query:

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

So below here is the code that is performing the same concept perfectly in 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;
    }
}

dont miss out iconCheck out another amazing blog by Manish here: Getting Started with Process Builder in Salesforce

Responses

Popular Salesforce Blogs