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
Vignesh RamshettyVignesh Ramshetty 

Count the clild object records based on picklist values

I have Customer_Policy_details__c  object which is child to Account object  it has masterdetail relationsip so, their is 
Policy_Status__c filed so it is picklist it has three values (Active, Expired,
Getting expired) and i have three fields in Account object  i.e,  Expired__c,  Acction_Required__C , Active_policies__c 
so, if status is changed to 
Getting expired or expired i have to update  i have to count the numbervof records which are in Expired, Getting expired , expired records count on account object  . with below code i am getting total number of records i need how many expired , how many are getting expired , how many are active  based on that number i should update 
 releated account record fields. 




Public class forcount{

Public Static void makefunction (List<Customer_Policy_details__c> varnewCon,List<Customer_Policy_details__c> varold){


                         map<Id,Customer_Policy_details__c> varmaplist = new map<Id,Customer_Policy_details__c>();
                         
                         
                         
     if (varnewCon != null){

         for(Customer_Policy_details__c varc : varnewCon){

                  if(varc.Account__c != null ){
                    
                  varmaplist.put(varc.Account__c,varc);

           }

       }

    }

  if (varold != null){

         for(Customer_Policy_details__c varcc : varold){

                       if(varcc.Account__c != null )
{
                    
                  varmaplist.put(varcc.Account__c,varcc);

           }

       }

    }

List<Account> varacclist = [SELECT id,Expired__c,Active_Policies__c,Acction_Required__c,(SELECT id,Policy_Status__c FROM Customer_Policy_details__r) FROM Account Where id in: varmaplist.keyset()];

    
    if(varacclist.size() > 0) {
                   
                        for(Account a : varacclist  ){
                            for(Customer_Policy_details__c csd:a.Customer_Policy_details__r)
{
system.debug('into this');
 system.debug('size'+a.Customer_Policy_details__r.size());
                             if(csd.Policy_Status__c == 'Expired'){

                           a.Expired__c = a.Customer_Policy_details__r.size();
          }

                 else if(csd.Policy_Status__c == 'Getting Expited'){

                           a.Acction_Required__c = a.Customer_Policy_details__r.size();

           }
              else   if(csd.Policy_Status__c == 'Active'){

                           a.Active_Policies__c = a.Customer_Policy_details__r.size();

           }
        }
}

       update varacclist; 

      }

  }

}