Salesforce Trigger for Count of Contacts Related to Account

by Rijwan Mohmmed
1 comment
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

You may also like

1 comment

myasin November 17, 2022 - 10:09 am

very easy to understand this code. thanks

Reply

Leave a Comment