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
Sainath VenkatSainath Venkat 

trigger to count child records

I am working on aq trigger which needs to count the child records.
I have two objects :
Contact and Relationships(API NAME- hed__Relationship__c), Relationships is having a lookup to contact with field name- "hed__Contact__c"
I have picklist field on Relationship object with API Name-"hed__Type__c" and if the values of the picklist are "Father" and "Mother"then I should count the relationship records that are assosited with the contact.

Can anyone helpme out in this please. Itried the below trigger but its not working on update and if I delete all the relationship records that are assosiated the the count is showing 1 where it should show 0.
Its working when I have two relationship records and when I delete 1 record count is becoming 1 but when I remove next one too then count is not becoming 0.
trigger UpdateOrder on hed__Relationship__c (after insert, after update, after delete, after undelete) {

   List<Contact> ct = new List<Contact>();
   
   Set<Id> custord = new Set<Id>();
   
   if(Trigger.isDelete) {
     for(hed__Relationship__c test:Trigger.Old) {
      
        custord.add(test.hed__Contact__c);   
    
     }   
   
   }
   else
   if(Trigger.isUpdate) {

     for(hed__Relationship__c test:Trigger.New) {
      
        custord.add(test.hed__Contact__c);  
    
     }

     for(hed__Relationship__c test:Trigger.Old) {
      
        custord.add(test.hed__Contact__c);   
    
     }   
   
   }
   else
   {
     for(hed__Relationship__c test:Trigger.New) {
      
        custord.add(test.hed__Contact__c);   
    
     }
   }
   
   AggregateResult[] groupedResults = [SELECT COUNT(Id), hed__Contact__c FROM hed__Relationship__c where hed__Type__c='Father || Mother' AND hed__Contact__c IN :custord GROUP BY hed__Contact__c ];
   
   for(AggregateResult ar:groupedResults) {
     
     Id custid = (ID)ar.get('hed__Contact__c');
     
     Integer count = (INTEGER)ar.get('expr0');
     
     Contact cust1 = new Contact(Id=custid);
     
     cust1.Number_Of_Dependents__c = count;
     
     ct.add(cust1);
      
   }
   
   
   update ct;

}

 
Best Answer chosen by Sainath Venkat
Manvendra Chaturvedi 26Manvendra Chaturvedi 26
Hi Sainath,

This should satisfy your requirement .

***Note ---  Please mark this as best answer if it's working as expected .

trigger ContactCount on hed_Relationship__c(after insert,after update,after delete){
    
    Map<Id, Decimal> conMap = new Map<Id, Decimal> ();    
    Map<Id,List<hed_Relationship__c>> mspconIdNdhedRel =new  Map<Id,List<hed_Relationship__c>>();
    set<ID> relationshipIdSet=new set<id>();    
    
    if(trigger.isafter){     
        if(trigger.isInsert){
            for(hed_Relationship__c con1:trigger.new){            
                if((con1.hed_Type__c=='Father' || con1.hed_Type__c=='Mother')  && trigger.isinsert){
                    relationshipIdSet.add(con1.hed_Contact__c);
                }
            }
        }  
        if(trigger.isUpdate){
            for(hed_Relationship__c con1:trigger.new){
                if(con1.hed_Type__c!=null && trigger.newmap.get(con1.id).hed_Type__c!=trigger.oldmap.get(con1.id).hed_Type__c){
                      relationshipIdSet.add(con1.hed_Contact__c);               
                } 
            }
        }                
        
        
        if(trigger.isDelete){
            for(hed_Relationship__c con1:trigger.old){
                if((con1.hed_Type__c=='Father' || con1.hed_Type__c=='Mother') && trigger.isdelete){
                    relationshipIdSet.add(con1.hed_Contact__c);
                }
            }
        }
        
        
        for(hed_Relationship__c hedRel: [Select id,hed_Contact__c from hed_Relationship__c where hed_Contact__c in : relationshipIdSet and (hed_Type__c='Father' OR hed_Type__c='Mother')] ){
            if(!mspconIdNdhedRel.containsKey(hedRel.hed_Contact__c)){
                mspconIdNdhedRel.put(hedRel.hed_Contact__c,new List<hed_Relationship__c>{});
            }
            mspconIdNdhedRel.get(hedRel.hed_Contact__c).add(hedRel);
        }
        
        system.debug('mspconIdNdhedRel-='+mspconIdNdhedRel);
        List<Contact> a1=new list<Contact>();    
        
        for(Contact con:[select id,Number_Of_Dependents__c  from Contact where ID in:mspconIdNdhedRel.keyset()]){    
            List<hed_Relationship__c> lst = mspconIdNdhedRel.get(con.id);
            
            system.debug('-='+lst.size() );
            con.Number_Of_Dependents__c =lst.size();   
            a1.add(con);            
        }    
        IF(a1.SIZE()>0){   
            update a1;   
        }
    }

}

All Answers

Manvendra Chaturvedi 26Manvendra Chaturvedi 26
trigger coninsertadd on hed__Relationship__c(after insert,after update,after delete){
    
    Map<Id, Decimal> conMap = new Map<Id, Decimal> ();    
    set<ID> relationshipIdSet=new set<id>();    
    
    if(trigger.isafter){       
        for(hed__Relationship__c con1:trigger.new){
            if((con1.hed__Type__c=='Father' || con1.hed__Type__c='Mother')  && trigger.isinsert){
                relationshipIdSet.add(con1.hed__Contact__c);
            }
            if((con1.hed__Type__c=='Father' || con1.hed__Type__c='Mother') && trigger.isupdate && trigger.newmap.get(con1.id).hed__Type__c!=trigger.oldmap.get(con1.id).hed__Type__c){
                relationshipIdSet.add(con1.hed__Contact__c);
            }            
        }
        for(hed__Relationship__c con1:trigger.old){
            if((con1.hed__Type__c=='Father' || con1.hed__Type__c='Mother') && trigger.isdelete){
                relationshipIdSet.add(con1.hed__Contact__c);
            }
        }
        
        for(AggregateResult  aggres:[select hed__Contact__c conId,Count() total from hed__Relationship__c where hed__Contact__c in:relationshipIdSet  group by hed__Contact__c])
        {
            conMap.put((ID)aggres.get('conId'),(Decimal)aggres.get('total'));           
        }     
        
        
        List<Contact> a1=new list<Contact>();    
        
        for(Contact acc:[select id,Number_Of_Dependents__c  from Contact where ID in:conMap.keyset()]){        
            acc.Number_Of_Dependents__c =(conMap.get(acc.id)!=null?conMap.get(acc.id):null);   
            a1.add(acc);            
        }    
        IF(a1.SIZE()>0){   
        update a1;   
        }
    }
}
Sainath VenkatSainath Venkat
Hello Manvendra Chaturvedi 26,

Thanks a lot for your quick reply but I am getting too many errors when I save your trigger. please find the below image which is having error messages.
User-added image
Manvendra Chaturvedi 26Manvendra Chaturvedi 26
Hi Sainath,

This should satisfy your requirement .

***Note ---  Please mark this as best answer if it's working as expected .

trigger ContactCount on hed_Relationship__c(after insert,after update,after delete){
    
    Map<Id, Decimal> conMap = new Map<Id, Decimal> ();    
    Map<Id,List<hed_Relationship__c>> mspconIdNdhedRel =new  Map<Id,List<hed_Relationship__c>>();
    set<ID> relationshipIdSet=new set<id>();    
    
    if(trigger.isafter){     
        if(trigger.isInsert){
            for(hed_Relationship__c con1:trigger.new){            
                if((con1.hed_Type__c=='Father' || con1.hed_Type__c=='Mother')  && trigger.isinsert){
                    relationshipIdSet.add(con1.hed_Contact__c);
                }
            }
        }  
        if(trigger.isUpdate){
            for(hed_Relationship__c con1:trigger.new){
                if(con1.hed_Type__c!=null && trigger.newmap.get(con1.id).hed_Type__c!=trigger.oldmap.get(con1.id).hed_Type__c){
                      relationshipIdSet.add(con1.hed_Contact__c);               
                } 
            }
        }                
        
        
        if(trigger.isDelete){
            for(hed_Relationship__c con1:trigger.old){
                if((con1.hed_Type__c=='Father' || con1.hed_Type__c=='Mother') && trigger.isdelete){
                    relationshipIdSet.add(con1.hed_Contact__c);
                }
            }
        }
        
        
        for(hed_Relationship__c hedRel: [Select id,hed_Contact__c from hed_Relationship__c where hed_Contact__c in : relationshipIdSet and (hed_Type__c='Father' OR hed_Type__c='Mother')] ){
            if(!mspconIdNdhedRel.containsKey(hedRel.hed_Contact__c)){
                mspconIdNdhedRel.put(hedRel.hed_Contact__c,new List<hed_Relationship__c>{});
            }
            mspconIdNdhedRel.get(hedRel.hed_Contact__c).add(hedRel);
        }
        
        system.debug('mspconIdNdhedRel-='+mspconIdNdhedRel);
        List<Contact> a1=new list<Contact>();    
        
        for(Contact con:[select id,Number_Of_Dependents__c  from Contact where ID in:mspconIdNdhedRel.keyset()]){    
            List<hed_Relationship__c> lst = mspconIdNdhedRel.get(con.id);
            
            system.debug('-='+lst.size() );
            con.Number_Of_Dependents__c =lst.size();   
            a1.add(con);            
        }    
        IF(a1.SIZE()>0){   
            update a1;   
        }
    }

}
This was selected as the best answer
Sainath VenkatSainath Venkat
Hello Manvendra,

I am getting the following error when I tried to save the new code that you have provided.
"Invalid type: Schema.hed_Relationship__c"
Manvendra Chaturvedi 26Manvendra Chaturvedi 26
Hi Sainath ,

Please varify object and Fields API name i have used in my code . Their might be possibility that API names didnot match.
Sainath VenkatSainath Venkat
Hello Manvendra Chaturvedi 26,
Thanks a lot for your time and almost everything works perfectly but I want to request onething here.
hed__Type__c has other picklist values also, on update if I change values to "Mother and Father" the count should increase and same if I change value from "Mother and Father" to other values then count should decrease which is not happening,
Can you help me out if possible please.
Manvendra Chaturvedi 26Manvendra Chaturvedi 26
Hi Sainath ,

I did verified the same and itsworking fine . When i am updating field value other the Mother or Father , it decreasing the count
Sainath VenkatSainath Venkat
Hello Manvendra,

Still I am having the same issue, when I delete all the child records count is still 1 and not becoming 0