Saturday, 18 January 2014

Roll Up Summary Trigger | COUNT

Roll Up Summary Trigger: Count Child Records.

Scenario:Count Total Contact records and display in Account Record in field-TotalContacts(Total_Contacts__c).

trigger ContactTrigger on Contact (after insert) {
     ContactTriggerHandler.countContacts(Trigger.new);
}

public class ContactTriggerHandler{
    public static void countContacts(List<Contact> contactList){
try{
Set<Id> accountIds = new Set<Id>();
for(Contact con:contactList){
accountIds.add(con.AccountId);
}    
Map<Id,List<Contact>> Map_accountId_contactList = new Map<id,List<Contact>>                                                                   ();
List<Account> accountList = new List<Account>();
accountList = [select ID, Total_Contacts__c,(SELECT id FROM Contacts) from                                                        Account WHERE Id IN:accountIds];
for(Account acc: accountList){
Map_accountId_contactList.put(acc.Id,acc.Contacts);
}
for(Account acc:accountList){  
    acc.Total_Contacts__c = (Map_accountId_contactList.get(acc.Id)).SIZE();
}
update accountList;
}
catch(Exception e){
system.Debug('An Error has occured::'+e.getMessage());
}
    }
}