Thursday, June 9, 2016

How to count number of child records in lookup relationship using trigger in Salesforce?

For Example Contact in my Child object and Account In my Parent Object.

trigger countTotalContactInAccount on Contact(after insert,after update,after delete){
set<Id> accountIDSet = new set<Id>();
list<Account> accountUpdateList = new list<Account>();
if(trigger.isInsert ){
for(Contact c:trigger.new){
      accountIDSet.add(c.AccountID);
}
if(trigger.isDelete || trigger.isUpdate){
for(Contact c:trigger.old){
     accountIDSet.add(c.AccountID);
}
}
list<Account> accountList = [SELECT id,name,(SELECT id from Contacts) from Account where ID IN : accountIDSet];
for(Account a:accountList){
a.Total_contacts__c = a.contacts.size();
accountUpdateList.add(a);
}
update accountUpdateList;

}


NOTE:- Total_contacts__c is a field(DataType - Number) in Account object which store total number of Contacts in a Account.

4 comments:

  1. And the code doest work for update!

    ReplyDelete
  2. what will be the query if the objects are custom objects

    ReplyDelete
  3. I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business. word counter

    ReplyDelete
  4. i tried same code for Lead & Event Object. Counts get updated if we enter any Event. But if i delete any Event, Count is not decreasing

    ReplyDelete

Common interview questions for Salesforce developers

Name three Governor Limits .                                                                                    Description Synchronous ...