Salesforce Trigger for Count of Contacts Related to Account

by Rijwan Mohmmed
5 comments
salesforce-trigger-for-count-of-contacts-related-to-account-techdicer

Hello friends, today we are going to discuss Salesforce Trigger for Count of Contacts Related to Account.

For best practice, we create a trigger and handler class. Handler class invoked by the trigger because for best practice we should write all logics in apex class, not in the trigger.

Also check this : How To Setup Prettier Apex VSCode

Code :

CountContactsOnAccount.apxt :

trigger CountContactsOnAccount on Contact (after insert, after update, after delete, after undelete) {
    //call handler for best practice
    if(Trigger.isinsert || Trigger.isupdate || trigger.isdelete || Trigger.isundelete){
        CountContactHandler.CountContactHelper(trigger.new, trigger.old);
    }
}

CountContactHandler.cls :

public class CountContactHandler {
    public static void CountContactHelper(List<contact> newcontact, List<contact> oldcontact){
        set<id> accIds= new set<id>();
        if(newcontact != null){
            for(Contact c : newcontact){
                if(c.AccountId!=null){
                    accids.add(c.accountid);
                }
            }      
        }
        
        if(oldcontact != null){
            for(Contact c : oldcontact){
                accids.add(c.accountid);
            }
        }
        
        List<Account> accList = [Select Id, NoofContacts__c, (Select id from Contacts) from Account where Id IN :accIds];
        
        if(accList!=null){
            for(Account acc : accList){
                acc.NoofContacts__c = acc.Contacts.size();
            } 
        }
        
        if(!accList.isEmpty()){
            update accList;
        }
    } 
}

Reference :

  1. Trigger
  2. Bulk Trigger
What’s your Reaction?
+1
11
+1
3
+1
1
+1
2
+1
4
+1
1

You may also like

5 comments

myasin November 17, 2022 - 10:09 am

very easy to understand this code. thanks

Reply
b February 7, 2023 - 11:15 am

Nested queries are counted against limits, this part can be solved using 1 query.
2nd thing, there is no need to check if accList is empty, salesforce is smart enough to not making dml on empty list.

Reply
Arvind December 27, 2023 - 6:07 am

Great work

Reply
Rijwan Mohmmed December 27, 2023 - 7:03 am

Thanks Arvind

Reply
ankit February 16, 2024 - 12:43 pm

If we are changing account of contact, it is not updating count on new account and previous account

Reply

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.