How to Count Number of Records in Related List and Display in Parent object Layout (Using Trigger) ?

Monday, September 19, 2016

How to Count Number of Records in Related List of Parent object and How to Display the Result in Parent Object Field (Using Apex Trigger) ?


Hi Guys,

After a long time i am here to share one post with you..

Here, I am Posting one Code for Counting No. of Records in Related list of Parent object and Display that Result in Custom field of Parent object..

Let's say i am counting here Number of Contact (Child) which is related to one Account (Parent)...

APEX TRIGGER CODE :

trigger countContact on Contact (after insert,after update) {

     Set<String> AccId = new Set<String>();
     
     List<Account> acc= new List<Account>();
     
     //Store the Temporary Account Id of the Child Contact
     for (Contact c1 : Trigger.New) {
        if (c1.AccountId != null) {
            AccId.add(c1.AccountId);
        }
    }
     
     // Functionality to Count Number of Contact available in Related Account
     for(Contact c : Trigger.New){
     
         List<AggregateResult> con =[SELECT AccountId aId, Count(Id)countContact FROM Contact WHERE AccountId IN : AccId GROUP BY AccountId];
         
         Integer contactCount = (Integer)con[0].get('countContact');
         
         System.debug('contact Count is ='+contactCount);
         
         // Store or Display Result of Counting Contact to Account's custom Field in Account Page Layout
         Account a = new Account();
         a.Id = (Id)con[0].get('aId');
         a.Contact_count__c = (Integer)con[0].get('countContact');
         acc.add(a);
         
     }
     
     update acc;
}



Cheers !!!!