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
Abby StockerAbby Stocker 

Trigger - Prevent user from closing a case if tasks are still open.

Hello! I have looked online for this and found 2 answers but neither truly make sense to me as to what the triggers are actually doing. I was wondering if someone could help me accomplish and understand an apex trigger. The requirement is that a case cannot be closed if it has an associated task that is still open. Thank you!!!!
Brandon NelsonBrandon Nelson
What I would do to start is write the logic for the IF statement

IF(current record field == X)
Then I would SOQL the TASK object where the WHATID = current record AND Status <> Completed. I would get a count of the task that match that criteria. If it is > 0, then display a warning to the user letting them know they have to close all task before they can select that option.

If my answer helped you, please mark as best

Brandon Nelson
Salesforce Admin/Developer
Abby StockerAbby Stocker
I apologize I am very new to the developer half of this life :) So, I would create a trigger on case..

trigger OpenTasksOnCase on Case (before update) {
   For(Case c : Trigger.New)
then SQL c for CaseNumber, Status when status <> Completed 
and SQL Task for WhatId, Status when status <> Closed
If record count of open tasks associated with case is >0, add error message displaying that they may not close the case with open tasks? 

Would you are anyone be able to assist on formatting this trigger? What the actual code should look like?
Deepali KulshresthaDeepali Kulshrestha
Hi Abby,

I've gone through your requirement and you can refer the below code or you can also use it for your requirement:
trigger OpenTasksOnCase on Case (before Delete)
{
OpenTasksOnCaseHandler.checkTaskOpenForCase(Trigger.Old);
}

public class OpenTasksOnCaseHandler
{
public static void checkTaskOpenForCase(List<Case> allcases)
{
try
{
 List<Case> allCaseHavingTask=new List<Case>();
 
 for(Case c:allcases)
 {
  if(c.Task__c!=null)
  {
    allCaseHavingTask.add(c);
  }
 }
 
 Map<id,Case> CaseMap=new Map<id,Case>();
 if(allCaseHavingTask.size()>0)
 {
   for(Case c:allCaseHavingTask)
   {
     CaseMap.put(c.id,c);
   }
 }
 
 for(Case c:allcases)
 {
   if(CaseMap.containsKey(c.id)
   {
     c.addError('Cant delete this Opportunity because it has open task');
   }
 }
}
catch(Exception e)
{
System.debug(e);
}
}
}


I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com