How to avoid closing Parent Case when child(related) cases are still open in Salesforce?

How to avoid closing Parent Case when child(related) cases are still open in Salesforce?

Sample Trigger:

trigger CaseTrigger on Case ( before update ) {
    
    Set < Id > setCaseIds = new Set < Id >();
    Map < Id, Integer > mapOpenCaseCount = new Map < Id, Integer >();
    
    for ( Case objCase : trigger.new ) {
        
        if ( objCase.Status == ‘Closed’ ) {
        
            setCaseIds.add( objCase.Id );
        
        }
    
    }
    
    for ( Case objCase : [ SELECT ParentId FROM Case WHERE ParentId IN: setCaseIds AND IsClosed = false ] ) {
    
        if ( mapOpenCaseCount.containsKey( objCase.ParentId ) ) {
        
            mapOpenCaseCount.put( objCase.ParentId, mapOpenCaseCount.get( objCase.ParentId ) + 1 );
        
        } else {
        
            mapOpenCaseCount.put( objCase.ParentId, 1 );
        
        }
    
    }    
    
    
    for ( Case objCase : trigger.new ) {
    
        if ( objCase.Status == ‘Closed’ ) {
        
            if ( mapOpenCaseCount.containsKey( objCase.Id ) ) {
        
                objCase.addError( ‘You cannot close this Case. It has ‘ + mapOpenCaseCount.get( objCase.Id ) + ‘ open Child Cases.’ );
                
            }
        
        }
    
    }

}


Sample Case record with two open Child Cases
 

Trigger Valiation Error:
 

Leave a Reply