Salesforce Apex: How to Track the Number of Contacts per Account

Tutorial using Apex Triggers and Classes

Jonathan Hsu
Code 85

--

The number of contacts per account is one of the first things anybody new to setting up Salesforce is interested in tracking. Unfortunately, a simple roll-up summary is not possible because the Contact sObject is a standard object.

Being unable to solve this requirement with a simple field, we need to use some of the Developer tools in Salesforce to auto-magically maintain this relationship between Account and Contacts.

In this tutorial we’ll use an Apex Trigger as the primary mechanism for tracking the number of contacts. Adjacent to the trigger, we’ll write the majority of our code in an Apex Class, setting us up for future updates and expansion.

Project Plan and Setup

This project will have three primary steps:

  1. Add a field to the Account sObject
  2. Write the Apex Class to be called in the Trigger
  3. Create the Apex Trigger

We’ll go through one step at a time, but if you’re the tl;dr type then there are links to the Apex Trigger and Apex Class along with an important warning at the bottom article.

Number of Contacts Field

--

--