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
mitsvikmitsvik 

How to Update parent case of record type A when the ASSOCIATED child record (rec type B) is closed

Requirement: if and only iff all the child cases (WITH RECORD TYPE B) are closed then automatically parent case record (rECORD TYPE A) should be closed.
I have written the following code, can some one tell me where i am wrong and also how do i query to suit the record type?

trigger Closeparentcaseauto on Case (before update) {
     Integer counter = 0;
    Set<Id> isparentID = new Set<Id>();----Create a set collection to get all the CHILD cases with parent ID
    
    for(Case cs : trigger.new)
        if(cs.ParentId!=null)
      isparentID.add(cs.ParentId);----From the trigger het the cases where parent id is not null and add it to the set collection.
      
      
      }
     ---loop through the    Cases with the above parent ID and put it in a list collection. ie: collect all the cases with parent ID.             

List<Case> cswithparentIDList = [SELECT Select Id,Status,ParentId From Case where status != 'Closed' and ParentId IN : isparentID];


    

---*/cswithparentIDList---Contains all the cases with the collected parents IDS. and also cases that is open.

---Create a map collection to get the Case with parent id and its child cases as a key value pair.

    Map<Id,List<Case>> caseListMapWithId = new Map<Id,List<Case>>();
    
    for (Case c: cswithparentIDList)
    
    if(caseListMapWithId.containskey(c.parentid)){
    
        caseListMapWithId.get(c.parentid).add(c);
        }else{
        caseListMapWithId.put(c.parentid,c);
        }
        }
        
    Now loop though the child case parent id and status open to loop through its child cases.
    
    for (Case c1: caseListMapWithId.values()){

    
                   
              
                if(c1.Status != 'closed')
                {
                  counter++;
                }
            
        }
         
    for (case  parentcase: cswithparentIDList) {
        
        
            parentcase.Status = 'Closed';
           
   
    }
    
    if (counter == 0){
    update parentcase;}

}
    
Andrew GAndrew G
//get Case Recordtype
	Schema.DescribeSObjectResult cfrSchemaCase = Schema.SObjectType.Case;
	Map<String,Schema.RecordTypeInfo> caseRecordTypeInfo = cfrSchemaCase.getRecordTypeInfosByName();
	Id recTypeCase = caseRecordTypeInfo.get('the name of my record type').getRecordTypeId();

	Set<Id> isparentID = new Set<Id>();
		for(Case cs : trigger.new) {
    	if(cs.ParentId!=null) {
  			isparentID.add(cs.ParentId);
    	}
	}
	List<Case> cswithparentIDList = [SELECT Id,Status,ParentId FROM Case 
		WHERE status != 'Closed' AND RecordTypeId = :recTypeCase.Id AND ParentId IN : isparentID];

That should take care of teh record Type for you.

Now you may need to think about the logic for comparing - that SELECT statement will return Open Cases for those Parent Ids.

You will now need to identify those record Ids that were in the original Set of Ids and the Ids of the parents that are returned.
SO perhaps create a Set of Parent Ids from the second list of Cases.  (These are Accounts with Open Cases).
and use the Contains method for Sets and test if the Id is in the first list but not in the second list, then there are no open cases.
Example 
for (Id id : isParentID) {
If (  !secondParentIDlist.contains(Id) ) {
update parentstatus;
}

regards
Andrew
 
mitsvikmitsvik
thank you will try
mitsvikmitsvik
Can you help me in my looping over child cases that have case parent ID? I have written it, but can you help

Public class CaseTriggerHandler
    {
        public void updateCase(List<Case> caseList, map<id, List<Case>> childwithparent))
           {
            Set<Id> setparentID = new Set<Id>();
             Integer count = 0;
            Id parentRecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Parent Record Type Name').getRecordTypeId();
            Id childRecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Child Record Type Name').getRecordTypeId();
     

         for(Case varCase : caseList)
         if(varCase.ParentId!=null && varCase.RecordTypeId= :childRecordTypeId.Id && varCase.status!=Null)
         setparentID.add(varCase.ParentId)

      }
         

         if(setParentID!=NULL && !setParentID.IsEmpty())
           {
        List<Case> casewithparentIDList = [SELECT Select Id,Status,ParentId From Case where ParentId IN : setParentID];
        
        
    
        for (Case childcases: casewithparentIDList)
    
    if(childwithparent.containskey(childcases.parentid)){
    
        List<Case> lstCases = childwithparent.get(childcases.parentid)
          lstCases.add(childcases)
          childwithparent.put(childcases.parentid,childcases);
          
        }else{
            
            
        caseListMapWithId.put(childcases.parentid,new List<Case> {childcases});

        }
        }
        
    
    
     List<case> toUpdate = new List<case>();

    
    
    for (Case childrencases: caseListMapWithId.keyset()){
        for (Case casevalues: caseListMapWithId.values()){
            
        
                        
    
                   count =0
              
                if(casevalues.Status == 'closed')
                {
                  count++;
                    system.debug('*****Countet Variable value***'+ count);
                }else 
        continue;
            
        }if(count == casevalues.size() ){

          childrencases.Status = 'Completed';

            toUpdate.add(childrencases);

        }

    }

    
    
    
Andrew GAndrew G
ok, if you are posting code, use the code sample button.   It makes the code easier to read as it doesn't lose it's formating etc.
image showing the code sample button (mouse hovering to show tool tip)
At first glance, i see that you are now trying to use a Handler.  With no idea of the structure of your trigger, my response is written as a trigger not Handler.
Also at first glance, you have a SELECT statment inside a FOR loop - this is a NO-NO.  The trigger would fail under bulk load.  Retaining the formatting would have made that easier to see.  
trigger Closeparentcaseauto on Case ( after update ) {
	//get Case Recordtype
	Id parentRecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Parent Record Type Name').getRecordTypeId();
	Id childRecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Child Record Type Name').getRecordTypeId();

    Set<Id> setparentID = new Set<Id>();             //setparentId holds all parents for the trigger cases
    List<Case> listOpenCases = new List<Case>();     //list of cases that are open and related to the parents
    Set<Id> setOpenParentID = new Set<Id>();         //set of parent ids where we have an open child case
    Set<Id> setParentsToUpdate = new Set<Id>();     //set of parent ids which we will mark closed
    List<Accout> listParents = new List<Account>(); // list of parent records to update

	for(Case cs : trigger.new) {
		if(cs.ParentId!=null) {
			setparentID.add(cs.ParentId);
		}
	}

	cswithparentIDList = [SELECT Id,Status,ParentId FROM Case 
		WHERE status != 'Closed' AND RecordTypeId = :childRecordTypeId.Id AND ParentId IN : isparentID];
	for (Case cs : cswithparentIDList ) {
		setOpenParentID.add(cs.ParentId);
	}

	for( Id id1 : setparentID ) {
		if ( !setOpenParentID.contains(id1) ) { 	//the id is not in the set of Ids for Parents with open children
			setParentsToUpdate.add(id1);			//so add the id to the list to be closed
		}
	}

	if (setParentsToUpdate!=null && !setParentsToUpdate.isEmpty()) {
		listParents = [SELECT Id,Status FROM Account 
		WHERE status != 'Closed' AND RecordTypeId = :parentRecordTypeId.Id AND ParentId IN : setParentsToUpdate];
		//filter query here for Closed status, we don't need to change it so we exclude them from the result
		// secondary note, depending on the behaviours of other triggers/validations, 
		// it may not be possible to have new Cases against Closed Accounts, so maybe not required.
	}

	if( !listParents).isEmpty()) {
		for(Account acct : listParents ) {
			acct.Status = 'Closed';
		}
		update listParents;
	}

}

Regards
Andrew
mitsvikmitsvik
This is my first ever trigger, so thank you for taking the time to correct it. I will implement and update you by next week.Appreciate it tottaly.