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 :
What’s your Reaction?
+1
4
+1
1
+1
1
+1
+1
1
+1
1
2 comments
very easy to understand this code. thanks
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.