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.