Update Number of Contact on Account

Write a trigger to update the number of related contact of the given account.

trigger contrigger on Contact (after update, after insert, after delete) {
    List<Contact> conlist = new List<Contact>();
    Set<id> accIdSet = new set<id>();
   
    if(trigger.isUpdate || trigger.isInsert)
        conlist = trigger.new;
    if(trigger.isDelete)
        conlist = trigger.old;
   
    for(contact c : conlist){
        if(c.AccountId != null)
                accIdSet.add(c.AccountId);
    }
   
    List<Account> acclist = new List<Account>();
    for(account acc : [Select Id,Number_Of_Contact__c, (select id from Contacts ) from account where id in :accIdSet ]){
        acc.Number_Of_Contact__c= acc.contacts.size();
        acclist.add(acc);
    }
    Database.update(acclist);
}




Comments

Popular Posts