+ Start a Discussion
Baz DensonBaz Denson 

trigger to prevent tasks being added to closed cases

Requirement Description

Requirement 1
Add business logic to Prevent a user from adding any other Task Record Types to a case with the status of Closed.

Add an error message to trigger on save of the task, if the user has added a Task where the WhatId relates to a case with a status of 'Closed'. The message to read 'Tasks cannot be added to Closed cases.'

Requirement 2
Add business logic to stop a user from adding an Event to a case with the status of Closed.

Add an error message to trigger on save of the event, if the user has added an Event where the WhatId relates to the case with a status of 'Closed'. The message to read 'Events cannot be added to Closed cases.'

I can't add it as a validation rule because WhatId is polymorphic.

Can anyone suggest the best approach.

Naveen KNNaveen KN
I think you have to go with the trigger. 

--
Naveen K N 
Baz DensonBaz Denson

Naveen

Can you give me a head start with the trigger code?

Thanks

Barry

Maharajan CMaharajan C
Hi Baz,

You can use the below triggers:

Task Trigger:
 
trigger PreventTaskCreation on Task (before insert) {

    set<Id> caseIdSet = new Set<Id>();
    for(Task t : Trigger.New){
        if(t.whatId!=null && String.valueOf(t.WhatId).startsWith('500')){
            caseIdSet.add(t.whatId);
        } 
    }
    
    if(!caseIdSet.isEmpty()){
        Map<Id,case> caseMap = new Map<Id,case>([Select Id,Status from case where Id IN: caseIdSet AND status = 'Closed']);
        if(!caseMap.isEmpty()){
            for(Task tsk:Trigger.New){
                if(caseMap.containsKey(tsk.whatId)){
                    tsk.addError('Task cannot be created under closed case');
                }
            }
        }
    }
}

Event Trigger:
 
trigger PreventEventCreation on Event (before insert) {

    set<Id> caseIdSet = new Set<Id>();
    for(Event e : Trigger.New){
        if(e.whatId!=null && String.valueOf(e.WhatId).startsWith('500')){
            caseIdSet.add(e.whatId);
        } 
    }
    
    if(!caseIdSet.isEmpty()){
        Map<Id,case> caseMap = new Map<Id,case>([Select Id,Status from case where Id IN: caseIdSet AND status = 'Closed']);
        if(!caseMap.isEmpty()){
            for(Event eve:Trigger.New){
                if(caseMap.containsKey(eve.whatId)){
                    eve.addError('Event cannot be created under closed case');
                }
            }
        }
    }
}

Thanks,
Maharajan.C