Displaying Total Number of Contacts for each Account in Salesforce

If you want to display the “Total Number of Contacts” for each “Account” in Salesforce on the Account page you can not use the Roll Up Summary field. The Roll Up Summary fields on contact are not supported on Accounts. We have used a Trigger on the contact object to  find the sum of the number of contacts which are there in an Account.

The trigger basically updates the Account custom field “Number_of_contacts__c” with the number of contacts that Account has. Since this trigger is on the Standard object it can be used in any Salesforce.com ORG by creating this custom field on Account.

The code below is developed based on Design pattern – ‘Factory Pattern’. For more information about this design pattern please refer this link.

This code has been modified recently

It works on delete of a contact and it also works even if you change the Account of a contact where it updates both the Accounts with the number of contacts.

Note: This code has been modified recently – please share your feedback. The previous code which had several issues is still hosted here.

About Sunil K

Sunil Khanna is the Founder, Principal Consultant, and CEO of Dhruvsoft, leading ERP and CRM consulting initiatives across Salesforce, Oracle NetSuite, and Zoho. With extensive global project experience spanning the USA, UK, Europe, India, and Australia, he helps organizations drive digital transformation through cloud technologies. Sunil brings deep expertise in business consulting, solution architecture, and application delivery, enabling businesses to optimize finance, operations, sales, marketing, and customer engagement processes.