
In the below example I have followed best practices to write logic for counting number of contacts on account object.
I have applied following points:
- Logic less trigger by using helper class
- Handled exception using try, catch
- Handled null point exception by putting null check
rollupOnContact.apxt
trigger rollupOnContact on Contact (after insert, after update, after delete, after undelete) {
if(Trigger.isinsert || Trigger.isupdate || trigger.isdelete || Trigger.isundelete){
Countcontact.Countcontacts(trigger.new,trigger.old);
}
}
Countcontact
Countcontacts.apxc
public class Countcontact {
public static void countcontacts(List<contact> newcontact,List<contact> oldcontact){
set<id> accids= new set<id>();
try{
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> acc = [Select id, NoofContacts__c,(Select id from Contacts) from Account where id IN: accids];
if(acc!=null){
for(Account accValue:acc){
accValue.NoofContacts__c = accValue.Contacts.size();
}
}
if(!acc.isempty()){
update acc;
}
}
catch(exception e){
System.debug('Get Message'+e.getMessage());
}
}
}
I hope you enjoyed this article. For more of these kind of articles stay tuned. Happy Coding !
Reference: