Display Custom Roll-up Summary on Account | Salesforce Developer Guide
In this blog, I would like you to share, how to display a custom roll-up summary on the account.
Before moving to code first create a custom field of number type “Associated_Contact_Count__c”. on Account object.
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, update, 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.
Don't forget to check out: Enhance Your Single View of The Customer Using Salesforce Marketing Cloud Connect
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;
}
}
Check out another amazing blog by Manish here: Email Studio in Salesforce Marketing Cloud | The Ultimate Guide
Responses