Wednesday, June 29, 2016

Number of Child Record Count on Parent Record Using Trigger

Number of Child Record Count on Parent Record Using Trigger

I use Account (this is parent) and Contact (this is chlid of Parent object which is Account)
this trigger work for all event like insert , update ,delete and undelete

Trigger ContactCountTrigger on Contact(After insert, After Delete, After Undelete, After Update)
{
  Set<Id> setAccountIds = new Set<Id>();

  if(Trigger.isInsert || Trigger.isUndelete){
for(Contact con : Trigger.new){
if(con.AccountID != Null)
            setAccountIds.add(con.AccountId);
    }
  }

  if(Trigger.isDelete){
     for(Contact con : Trigger.old){
    if(con.AccountID != Null){
                 setAccountIds.add(con.AccountId);
             }
     }
  }

  if(Trigger.isUpdate){
     for(Contact con : Trigger.New){
    if(con.AccountID != Null){
                 setAccountIds.add(con.AccountId);
     }
            if(Trigger.oldMap.get(con.Id).AccountId != null){
                 setAccountIds.add(Trigger.oldMap.get(con.Id).AccountId);
            }
      }
  }

 List<Account> listAccs = [SELECT id,name,number_of_contacts__c ,(Select id from contacts) FROM Account WHERE Id in : setAccountIds];

//number_of_contacts__c this is Number type Field  on account object
//contacts is a child relationship name
  for(Account acc :listAccs){
      acc.number_of_contacts__c = acc.contacts.size();
  }
  update listAccs;
}

No comments:

Post a Comment