Tuesday, March 1, 2016

Number of Child Record Count on Parent Record Using Trigger

I want to display count of the Contacts related to particular Account on a field in Account object.I want to make sure that it will work properly when I inserted new Contact or Deleted or Undelete also.In this post i'm going to explain how to implement this in Step by Step.

Choose he Right Object for Trigger
If you have doubt on which object I need to write trigger whether it's on Contact or Account object?My answer is blindly Contact because here we are going to track the number of contacts so it means that we need to have a glance on each and every change on a contact object.So we have to write a trigger on Contact Object

Source Code of the Trigger
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;
}


OutPut:



Notes:
1.Whenever your working with Undelete operation in Trigger you have to make sure that you have to use only Trigger.new or Trigger.newMap context variables to get the run time values of records.

2.Apex will treats Undelete operation as an insert operation so if you refer any Trigger.old or Trigger.oldMap you will not get any data so you will end up with an System.NullPointerException:Attempt to de-reference a null object

3. In after delete operation if you refer any Trigger.new you will be end with an same System.NullPointerException:Attempt to de-reference a null object because Trigger.new will support only Insert and Update operation .So we have to Trigger.old here.
Enjoy.......!!!



No comments: