Newer Version Available

This content describes an older version of this product. View Latest

Apex Trigger: Auto-Close Cases with Closed Work Orders

The following trigger automatically closes cases when a work order linked to the case is marked Closed. It saves support agents from having to manually close a case after the related work is complete.

If a case has multiple work orders, the trigger fires the first time any related work order is marked Closed.

Note

1trigger CloseCaseOnWorkOrderUpdate on WorkOrder (after update) {
2    // Query all the cases whose work order ID is the incoming work order
3    List<Case> casesToUpdate = [select Id, Status from Case 
4                               where Id IN (select caseId from WorkOrder 
5                                            where Id IN :Trigger.newMap.keySet() 
6                                            and Status ='closed')];             
7	// Set the case status to closed 
8    for (Case c : casesToUpdate) {
9        c.status = 'closed';
10    }
11    update casesToUpdate;
12}
You can set up Apex unit tests in the developer console to scan your code for any issues. To keep things running smoothly, Salesforce requires at least three-quarters of your Apex code lines to be covered by tests. The following unit test applies to this trigger.
1@isTest
2private class WOTriggerTest {
3    static testMethod void validateWO() {
4    Case ca = new Case();
5    ca.Origin ='Phone';
6    ca.Status ='new';
7    insert(ca);
8        WorkOrder wo = new WorkOrder();
9        wo.Subject = 'test';
10        wo.Status ='closed';
11        wo.CaseId = ca.Id;
12        insert(wo);
13        update(wo);
14        Case ca1 = [SELECT Status from Case where id= :ca.Id];
15        System.assertEquals('Closed', ca1.Status);
16    }
17}