Skip to main content
1 of 3

Prevent to create a task when a case is closed

how's it going?

Basically what I need is to prevent a task being created when a case status is 'Closed'.I'm struggling with my code, I just can't get the right Id of the case where I'm creating a task. I'm going to explain what I did and what I got so far:

  1. Take a look at the first picture below, and see that the Case id is "5003i000001nd7YAAQ" and the "Status" field is populated with "Closed".

enter image description here

  1. I clicked on the option "New Task" in the related list "Open Activities" and then I tried to create a task. Then the trigger message error pops up. It's ok by then...

enter image description here

...but when I was viewing the debug log (Code 1) I noticed that the Case id was not equals to "5003i000001nd7YAAQ", it was actually "5003i000001nd7KAAQ".

After trying to create a new task the trigger was activated

I tried a lot of things to get this over, but I just couldn't get this done. I don't know another way of meeting this goal unless using trigger, but I'm a newbie at coding. I used "before insert" to my trigger. Look at my first and second code below:

Code 1

Trigger CaseClosed on Task(Before Insert) {    
    List<Case> mySOQL = [SELECT Status FROM Case WHERE Status = 'Closed'];
    
    String temp0 = mySOQL[0].status; String temp1 = mySOQL[0].Id;
    System.debug(temp0); 
    System.debug(temp1);
    
    for (Task a : Trigger.new) {
        if('Closed'.equals(temp0)){
            a.addError('Is not allowed to create tasks when a case is closed.');
        }               
    }      
} 

Code 2 - It also didn't return the right case Id

Trigger CaseClosed on Task(Before Insert) {    
                List<Task> lstTask = [SELECT WhatId FROM Task 
                                      WHERE What.Type = 'Case'
                                      ORDER BY SystemModStamp ASC];
                System.debug(lstTask);    
            }

This two codes was the closest I've got. I tried other things, but it was way off the mark. Could you please help me out? I don't know what to do.