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
smriti sharan19smriti sharan19 

How to write a trigger when case status is closed- all task should be completed and when all task are completed then case should get closed?

How to write a trigger when case status is closed then all task should be completed and when all task are completed then case should get closed?
Raj VakatiRaj Vakati
Try this
 
trigger AssignmentRulesonCaseTrigger on Case (before update)
 {
  
            for (Case theCase:trigger.new) 
            {
				if(theCase.status=='Closed'){
					List<Task> ts = [SELECT WhatId FROM Task 
					WHERE WhatId =:theCase.Id 
					and What.Type = 'Case'];
					if(ts.size()>0){
					ts.adderror('Please close the task before closing case');	
					}
	 
				}
             }
			 
		 


  
}

 
Amit Chaudhary 8Amit Chaudhary 8
Hi Raj Vakati / smriti shararan,

Never write SOQL inside the for loop. Update this code like below
 
trigger AssignmentRulesonCaseTrigger on Case (before update) {

	Set<Id> setCaseId = new Set<Id>();
	for (Case theCase:trigger.new) {
		if(theCase.status=='Closed'){
			setCaseId.add(theCase.id);
		}
	}
	
	if(setCaseId.size() > 0 ){
	
		List<Task> lstTask = [SELECT WhatId,id 
								FROM Task 
								WHERE WhatId in :setCaseId 
								and What.Type = 'Case'
								and IsClosed  = false];
	
		Map< String, List<Task> > mapCaseWiseTask = new Map< String, List<Task> >();
		for(Task ts : lstTask){
			if( mapCaseWiseTask.containsKey(ts.WhatId) ){
				List<Task> lstT = mapCaseWiseTask.get(ts.WhatId);
				lstT.add(ts);
			}else {
				List<Task> lstT = new List<Task>();
				lstT.add(ts);
				mapCaseWiseTask.put( ts.WhatId , lstT );
			}
		}
		
		for( Case theCase : trigger.new ) 
		{
			if(theCase.status=='Closed' && mapCaseWiseTask.containsKey(theCase.id) ){
				theCase.adderror('Please close the task before closing case');	
			}
		}
	}
	
}

Let us know if this will help you