+ Start a Discussion
akkkakkk 

is it possible to count the child record for each parent Records on the Child Object with Trigger

Hi all,

Plese uspport how to count the each child record for each parent records on child object with trigger
ex->
child record 5 for 1 parent record but count on the Child object
child record 2 for other 1 parent record but count on the Child object

Thanks
akkk
 
AnudeepAnudeep (Salesforce Developers) 
Here is a code sample on child Object
 
Trigger ContactCountTrigger on Contact(After insert,After Delete,After Undelete)
{
  Set<Id> setAccountIds = new Set<Id>();
  
  //Whenever your working with After Undelete operation you can access data through 
  //Trigger.new or Trigger.newMap but not with Trigger.old or Trigger.oldmap variables
  if(Trigger.isInsert || Trigger.isUndelete)
  {
   for(Contact con : Trigger.new)
   {
    setAccountIds.add(con.AccountId);
   }
  }
  
  if(Trigger.isDelete)
  {
   //if you use Trigger.new below in place of Trigger.old you will end up with 
   //System.NullPointerException:Attempt to de-reference a null object
   for(Contact con : Trigger.old) 
   {
    setAccountIds.add(con.AccountId);
   }
  }
  
 List<Account> listAccs = [Select id,name,number_of_contacts__c ,(Select id from contacts) from Account where Id in : setAccountIds];
  for(Account acc :listAccs)
  {
   acc.number_of_contacts__c = acc.contacts.size();
  }
  update listAccs;
}

Let me know if this helps, if it does, please mark this answer as best so that others facing the same issue will find this information useful. Thank you
 
akkkakkk
Hi Anudeep

it is not like my query because i want to (sum of count on child record not on the Prarent record).
your code working fine but count the sum of child record on parent object but want to sum of record update on child object


Thanks
akkk