Saturday, September 7, 2019

How To Store Count of Child Records in Parent Record


If the Parent & Child object is related with Master-Detail Relationship, we can easily get 

the count of Child records and store it in the Parent object by using Roll-up Summary 

field. But if the relation is Lookup between the Parent & Child, we don't have any other 

option except writing Trigger. So for example I am taking Account & Contact object as these 

are related with Lookup. So we need to Count all the Contact records and store it into 

the respective Parent Account record.

Question: In Which Object should I write the Trigger?

Answer: Ofcourse the answer would be Contact object as when we are performing any 

DML Operation on Contact record, the count of contact records will be affected and by 

implementing a Trigger on Contact object, we can easily capture the Count and update it 

to the respective Parent Account record.

So the answer is we have to implement the Trigger obviously in Child Object.



Please find the Trigger code below:


    trigger totalContactsTrigger on Contact (After Insert,After Update,
    After Delete,After Undelete) {        
    Set<IdsetAccIds = new Set<Id>();
    //Using Trigger.new to get the Account Id for Insert & undelete Operation
    if(Trigger.isInsert || Trigger.isUndelete){    
        for(Contact con : Trigger.new){
            setAccIds.add(con.AccountId);
        }
    }    
    //Using Trigger.new & Trigger.old to get older & newer version of Account Id
    if(Trigger.isUpdate){
        for(Contact con : Trigger.new){ 
            //Condition to check if the Account lookup field is updated or not
            if(con.AccountId!=Trigger.oldMap.get(con.Id).AccountId){
                setAccIds.add(con.AccountId);
                setAccIds.add(Trigger.oldMap.get(con.Id).AccountId);
            }        
        }
    }
    //Using Trigger.old to get the Account Id for Delete Operation  
    if(Trigger.isDelete){ 
        for(Contact con : Trigger.old) {  
            setAccIds.add(con.AccountId);
        }
    }    
    List<AccountaccList=new List<Account>();  
    for(Account acc :[Select id,Total_Contacts__c ,(Select id from contactsfrom 
    Account where Id in : setAccIds]){
        acc.Total_Contacts__c = acc.contacts.size();
        accList.add(acc);
    }
    if(!accList.isEmpty()){ 
        update accList;
    }        
   }



2 comments: