Display total number of contacts associated with an account.

In this part, I am going to explain how to calculate the total number of contacts associated with an account object in a very simple way. After calculating the total number of contacts you can display this totals in a field of an account object. 
This trigger works in all scenario after insert, after delete, after Undelete and after update.

Requirement --

Create a Number type field named NumberOfContact on account object.


Trigger --

trigger NumberOfContactOnAccount on Contact (after insert,after update,after delete,after undelete) 
{
    set<Id> ids = new set<Id>();
    
    if(Trigger.isInsert)
    {
        for(Contact c : Trigger.new)
        {
            if(c.AccountId != null)
            {
                ids.add(c.AccountId);
            }
        }
    }
    
    if(Trigger.isDelete || Trigger.isUpdate)
    {
        for(Contact c : Trigger.old)
        {
            if(c.AccountId != null)
            {
                ids.add(c.AccountId);
            }
        }
    }
    if(Trigger.isUndelete)
    {
        for(Contact c : Trigger.new)
        {
            if(c.AccountId != null)
            {
                ids.add(c.AccountId);
            }
        }
    }
    
    List<Account> displayList = new List<Account>(); 
    List<Account> acList = [select id,Number_Of_Contact__c,(select id,name from contacts) from account where Id IN: ids];
    
    for(Account a : acList)
    {       
                  
          a.Number_Of_Contact__c = a.contacts.size();
          displayList.add(a);
        
        
    }
    update displayList;

}

Comments

Popular posts from this blog

How to show or hide a particular section of Visualforce Page dependent upon picklistfield value

Process Automation Specialist Superbadge

Dynamically Add/Delete rows in Visualforce Page