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
bhanu_prakashbhanu_prakash 

Update account status based on related list

Hi ,

Need to update In account I have a list contact in realted list , when all contacts status__c is active. I need to update account status as active.if any one contact is inactive need to update account status as inactive ..how can we achecive it ?
Help me to write trigger 
sfdc TrailHeadssfdc TrailHeads
Hi Bhanu,
//Trigger
trigger AllContactsStatusIsActiveThanAccountStatusIsActive on Contact (after insert,after update)
{
    if(trigger.IsAfter && trigger.IsUpdate)
    {
     AccStatusUpdtUsingAllConsStatusHandler obj = new AccStatusUpdtUsingAllConsStatusHandler();
    obj.OnAfterUpdate(trigger.new);
   
    }
}

//Handler
public class ParenrtCaseUpdtUsingAllChildCasesHandler {
    public void OnUpdate(List<case> lstCases)
    {
       OnAfterUpdate(lstCases);
    }
    public void OnAfterUpdate(List<case> lstCases) {
        Integer TotalCount =0;
        Integer childCount =0;
        Set<id> parentCaseId = new Set<id>();
        for(case childcase : lstCases) {
            parentCaseId.add(childcase.ParentId);
        }
        
        List<case> lstParentCaseUpdt = new List<case>();
        
        list<Case> lstCase = [select id,Status,parentId
                              FROM case
                              where parentId =:parentCaseId];
        if(lstCase.size()>0)
        {
            TotalCount = lstCase.size();
        }
        system.debug('=====Total child case===>'+TotalCount);
        
        Set<id> parentcaslstId = new  Set<id>();
        
        for(Case c :lstCase)
        {
            if(c.Status == 'Closed')
            {
                childCount++;
                system.debug('=======>'+childCount);
                
                if(childCount == TotalCount)
                {
                    system.debug('==Both counts are equal====');
                    parentcaslstId.add(c.ParentId);
                    
                }
                else
                {
                    system.debug('==Both counts are Not equal====');
                }
            }
        }
        for(Case parentCase :[select id,Status
                              FROM case
                              where Id =:parentcaslstId] )
        {
            parentCase.Status = 'Closed';
            lstParentCaseUpdt.add(parentCase);
        }
        update lstParentCaseUpdt;
    }
}