Print this page

Display the total number of contacts on account detail page

Knowledge Article Number 000003089

If you're trying to display the total number of contacts on an account detail page you'll need to use Visualforce and an extension. We'll give you an overview of how to do this, and show you some sample code that you may be able to modify and use for your organization.


Sample Visualforce markup code


<apex:page standardController="account" extensions="contactsOnAccountsExtension">
<apex:outputLabel value="The total number of contacts on Account is: "/>
<apex:outputText value="{!sum}"/>

This code should be augmented to improve it's look and how well it fits into the account detail page. The extension that is required for the above Visualforce page could look like this:

public class contactsOnAccountsExtension{
private final Account acct;
public Integer sum {get; set;}

        public contactsOnAccountsExtension(ApexPages.StandardController stdController) {
        this.acct = (Account)stdController.getRecord();
        sum = [SELECT count() FROM Contact WHERE AccountId =:acct.Id];            

Remember this is sample code, you may need to modify it for use in your organization.

This code is very simple, but does return the total number of contacts on an account, but further enhancements could be imagined and easily added. Additionally, this code hasn't been tested, this would need to happen in a full sandbox to make sure that it worked without issue.


Display Visualforce page as part of the account detail page


 1. Click Setup.
 2. Click App Setup | Customize | Accounts 
 3. Click Page Layouts | then select the layout.
 4. Select Visualforce pages from the palette and drag the Visualforce page above to an appropriate position on the layout.
 5. Save the layout.

promote demote