function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
jayshree kbjayshree kb 

trigger for count in lookup relationship

I I have two custom obj one is called Parent and the other Child..lookup relationship exists between the two obj..i want to count the child records for each parent and update it in a field named "ContactsCount"..I facing some exception error when tryin to insert Child records..below is the code
trigger ConCount on Child__c (after insert) {
Set <id> CHildIds = new set<id>();
List<Child__c> ChildList = new List<Child__c>();
List<Child__c> ListCon = new List<Child__c>();
List<Parent__c> ParentList = new List <Parent__c>();
List<Parent__c> ListParent = new List <Parent__c>();
Map<id,integer> ConMap = new map <id,integer>();
if(Trigger.isInsert){
    for(Child__c Chil : Trigger.New){
    CHildIds.add(Chil.Parentlookup__c);}   
    ParentList = [select id, name from Parent__c where id IN :CHildIds];
    ChildList = [select id,name , Parentlookup__c from Child__c where Parentlookup__c IN :CHildIds];
        for(Parent__c P :ParentList){
        Listcon.clear();
        for(Child__c C : ChildList){
        if(C.Parentlookup__c == P.id){
        ListCon.add(C);
         ConMap.put(P.id,ListCon.size());
         
         } }}
        if(ParentList.size()>0){
        for(Parent__c Pa : ParentList){
        if(ConMap.size()>0){
        Pa.ContactsCount__c = ConMap.get(Pa.id);
        ListParent.add(Pa);
        }}}
        if(ListParent.size()>0)
        update ListParent;
        }}

 
Best Answer chosen by jayshree kb
Pranav ChitransPranav Chitrans
Hi Jayshree,

Please find the below code :

Apex Trigger
trigger CountChildForEachParent on Child__c (after insert, after update, after delete, after undelete)  
{
    HandlerForChildToCountRecords handler = new HandlerForChildToCountRecords ();
    handler.run();
}
Apex Class
public class HandlerForChildToCountRecords 
{    
    public void run()
    {
        if(trigger.isInsert || trigger.isUpdate && trigger.isAfter)
        {   
            afterInsertMethod(trigger.new);
        }
        
        if(trigger.isDelete  && trigger.isAfter)
        {   
            afterDeleteMethod(trigger.new,trigger.old);
        }
        
        if(trigger.isUpdate && trigger.isAfter)
        {   
            afterUpdateMethod( trigger.new, trigger.OldMap);
        }
    }
    
    private void afterInsertMethod(list<child__c>triggerNew)
    {
        //commonMethod(triggerNew,null);
        set<id> setOfId  = new set<id>();           
        for(child__c objChildNew : triggerNew)
        {
            if(objChildNew.Parent_name__c != null)
            {
                setOfId.add(objChildNew.Parent_name__c);
                system.debug('*****setOfId'+setOfId);
            }
        }
        if(setOfId.size() > 0)
        {
            //calling commom method to perofrm the operation, so as to reduce the line of code
            commonMethod(setOfId);
        }
    }
    
    private void afterDeleteMethod(list<child__c>triggerNew,list<child__c>triggerOld)
    {
        set<id> setOfId = new set<id>();           
        for(child__c objChildNew : triggerOld)
        {
            if(objChildNew.Parent_name__c != null)
            {
                setOfId.add(objChildNew.Parent_name__c);
                system.debug('*****setOfId'+setOfId);
            }
        }
        if(setOfId.size() > 0)
        {
            //calling commom method to perofrm the operation, so as to reduce the line of code
            commonMethod(setOfId);
        }
    }
    
    //Common Method to perform insertion/updation/deletion to query records
    private void commonMethod(set<id> setOfId)
    {
        try
        {           
            list<Parent__c> lstOfParent = new list<Parent__c>([select id,name,ContactsCount__c ,(select id,name from Child__r)
                                                                                                         from 
                                                                                                        Parent__c 
                                                                                                    where id IN:setOfId]);
            system.debug('*****lstOfParent'+lstOfParent);
            for(Parent__c objPrnt : lstOfParent)
            {
                if(objPrnt.ContactsCount__c != objPrnt.Child__r.size())
                {
                    objPrnt.ContactsCount__c = objPrnt.Child__r.size();
                }
            }
            update lstOfParent;
        }
        
        catch(DmlException e)
        {
            system.debug('The following exception has occurred: ' + e.getMessage()); 
        }  
    }
    
    Public void afterUpdateMethod( list<sobject> triggerNew, map<id,sobject> triggerOldMap)
    {
        set<id> setOfId = new set<id>();    
        
        list<child__c> lstChild = (list<child__c>) triggerNew;
        map<id, child__c> mapChild = (map<id, child__c>) triggerOldMap;
        for(child__c childObj : lstChild)
        {
            if(childObj.Parent_name__c != null && mapChild.get(childObj.id).Parent_name__c != null && childObj.Parent_name__c != mapChild.get(childObj.id).Parent_name__c)
            {
                setOfId.add(childObj.Parent_name__c);
                setOfId.add(mapChild.get(childObj.id).Parent_name__c);
            }
        }
        
        if(setOfId.size() > 0)
        {
            //calling commom method to perofrm the operation, so as to reduce the line of code
            commonMethod(setOfId);
        }
    }
        
}

It will also work if some child parent gets changed or child gets deleted.

Thanks
Pranav

All Answers

Amit Chaudhary 8Amit Chaudhary 8

Please check below code and update your code
trigger ContactTrigger on Contact (after insert, after update, after delete, after undelete) {
    //---> above handling all states which could see a contact added to or removed from an account
   
    //---> on delete we use Trigger.Old, all else, Trigger.new
    List<Contact> contacts = Trigger.isDelete ? Trigger.old : Trigger.new;

    //---> the Set class rocks for finding the unique values in a list
    Set<Id> acctIds = new Set<Id>();
   
    for (Contact c : contacts) {
     //yes, you can have a contact without an account
        if (c.AccountId != null) {
            acctIds.add(c.AccountId);
        }
    }
   
    List<Account> acctsToRollup = new List<Account>();
    
    //****** Here is the Aggregate query...don't count in loops, let the DB do it for you*****
    for (AggregateResult ar : [SELECT AccountId AcctId, Count(id) ContactCount 
                               FROM Contact 
                               WHERE AccountId in: acctIds 
                               GROUP BY AccountId]){
        Account a = new Account();
        a.Id = (Id) ar.get('AcctId'); //---> handy trick for updates, set the id and update
        a.Contact_Count__c = (Integer) ar.get('ContactCount');
        acctsToRollup.add(a);
    }
    
    //----> probably you'll want to do a little more error handling than this...but this should work. 
    update acctsToRollup;

}

Let us know if this will help you
 
Vinuthh SVinuthh S
Hi Jayshree

Try the below Code.

trigger ConCount on Child__c (after insert) {
for(Parent__c Parent:Trigger.New){
   List<Child__c> ChildList = [select id from Child__c where Parentlookup__c=:Parent.Id];
   Integer Count = ChildList.Size();
   Parent.ContactsCount = Count;
   update Parent;
}
}
\
Thanks
Vinuthh S
Pranav ChitransPranav Chitrans
Hi Jayshree,

Please find the below code :

Apex Trigger
trigger CountChildForEachParent on Child__c (after insert, after update, after delete, after undelete)  
{
    HandlerForChildToCountRecords handler = new HandlerForChildToCountRecords ();
    handler.run();
}
Apex Class
public class HandlerForChildToCountRecords 
{    
    public void run()
    {
        if(trigger.isInsert || trigger.isUpdate && trigger.isAfter)
        {   
            afterInsertMethod(trigger.new);
        }
        
        if(trigger.isDelete  && trigger.isAfter)
        {   
            afterDeleteMethod(trigger.new,trigger.old);
        }
        
        if(trigger.isUpdate && trigger.isAfter)
        {   
            afterUpdateMethod( trigger.new, trigger.OldMap);
        }
    }
    
    private void afterInsertMethod(list<child__c>triggerNew)
    {
        //commonMethod(triggerNew,null);
        set<id> setOfId  = new set<id>();           
        for(child__c objChildNew : triggerNew)
        {
            if(objChildNew.Parent_name__c != null)
            {
                setOfId.add(objChildNew.Parent_name__c);
                system.debug('*****setOfId'+setOfId);
            }
        }
        if(setOfId.size() > 0)
        {
            //calling commom method to perofrm the operation, so as to reduce the line of code
            commonMethod(setOfId);
        }
    }
    
    private void afterDeleteMethod(list<child__c>triggerNew,list<child__c>triggerOld)
    {
        set<id> setOfId = new set<id>();           
        for(child__c objChildNew : triggerOld)
        {
            if(objChildNew.Parent_name__c != null)
            {
                setOfId.add(objChildNew.Parent_name__c);
                system.debug('*****setOfId'+setOfId);
            }
        }
        if(setOfId.size() > 0)
        {
            //calling commom method to perofrm the operation, so as to reduce the line of code
            commonMethod(setOfId);
        }
    }
    
    //Common Method to perform insertion/updation/deletion to query records
    private void commonMethod(set<id> setOfId)
    {
        try
        {           
            list<Parent__c> lstOfParent = new list<Parent__c>([select id,name,ContactsCount__c ,(select id,name from Child__r)
                                                                                                         from 
                                                                                                        Parent__c 
                                                                                                    where id IN:setOfId]);
            system.debug('*****lstOfParent'+lstOfParent);
            for(Parent__c objPrnt : lstOfParent)
            {
                if(objPrnt.ContactsCount__c != objPrnt.Child__r.size())
                {
                    objPrnt.ContactsCount__c = objPrnt.Child__r.size();
                }
            }
            update lstOfParent;
        }
        
        catch(DmlException e)
        {
            system.debug('The following exception has occurred: ' + e.getMessage()); 
        }  
    }
    
    Public void afterUpdateMethod( list<sobject> triggerNew, map<id,sobject> triggerOldMap)
    {
        set<id> setOfId = new set<id>();    
        
        list<child__c> lstChild = (list<child__c>) triggerNew;
        map<id, child__c> mapChild = (map<id, child__c>) triggerOldMap;
        for(child__c childObj : lstChild)
        {
            if(childObj.Parent_name__c != null && mapChild.get(childObj.id).Parent_name__c != null && childObj.Parent_name__c != mapChild.get(childObj.id).Parent_name__c)
            {
                setOfId.add(childObj.Parent_name__c);
                setOfId.add(mapChild.get(childObj.id).Parent_name__c);
            }
        }
        
        if(setOfId.size() > 0)
        {
            //calling commom method to perofrm the operation, so as to reduce the line of code
            commonMethod(setOfId);
        }
    }
        
}

It will also work if some child parent gets changed or child gets deleted.

Thanks
Pranav
This was selected as the best answer