In the below example I have followed best practices to write logic for counting number of contacts on account object. Please understand carefully as it is very common question in interviews.
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); } }
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()); } } }
cont no of contact on acc
Account A -> 2 con
no of contact = 2
Account B -> 1 con ,
Account B is parent of A
no of contact => 3
Account C -> 2 con ,
C is parent of B
no of contact => 5
how to achieve this requirement