Site icon Popular In India

Count Number of Contacts on Account in Salesforce using Trigger

Hello everyone today we are going to discuss here how to Count Number of contacts on account in salesforce using Trigger.

Salesforce Apex Trigger Code Best Practices:

Create only one trigger per sObjectType.
This makes it easier to maintain your code.
Use logic-less triggers.
Instead of writing all your logic in the trigger, delegate the logic to a handler class.
Use context-specific handler methods.
This makes it easier to understand what your code is doing.
Avoid SOQL queries inside for loops.
This can cause performance issues.
Avoid hardcoding IDs.
Instead, use custom settings or metadata.
Avoid nested for loops.
This can cause performance issues.
Avoid DML inside for loops.
This can cause performance issues.
Bulkify your code.
This means that your code should be able to handle bulk operations.

Step1: Create one field in Account object with name No of Contacts.

Go to Setup> Object Manager > Account Object > Account

Account>Fields & Relationship > Click New

Select Text option then below window open

Click next below window open

Again click on next then final click on save and new field created successfully.

Step 02: Create trigger with name β€œNumberOfContactOnAccount” on developer console with below code.

trigger numberOfContactOnAccount on Contact(after insert, after update, after delete, after undelete){
if(Trigger.isInsert || Trigger.isupdate || trigger.isdelete || Trigger.isundelete){
CountNumberOfContactHelper.CountNumberOfContactHelper(trigger.new, trigger.old);
}
}

Step 03: Create helper Class with name CountNumberOfContactHelper.apex

public class CountNumberOfContactHelper{
public static void CountNumberOfContactHelper(List newContact, List oldContact){
Set<Id> accIds = new Set<Id>();
if(newContact != null){
for(Contact con: newContact){
if(con.AccountId != null){
accIds.add(con.AccountId);
}
}
}

if(oldContact != null){
for(Contact oCon: oldContact){
if(oCon.AccountId != null){
accIds.add(oCon.AccountId);
}
}
}

List<Account> accList= [Select Id, No_of_Contacts__c, (Select Id from Contacts) from Account where Id IN : accIds];

if(accList != null){
for(Account acc: accoList){
acc.No_of_Contacts__c= acc.Contacts.size();
}
}

if(!accList.isEmpty()){
update accList;
}

}
}

Exit mobile version