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 CloseCaseWhenWoId on WorkOrder (after update) {
2    for (WorkOrder wo: Trigger.new) {
3        try {
4            if (wo.Status == 'closed') {
5                Case ca = [SELECT Status from case where id = :wo.CaseId];
6                ca.Status ='closed';
7                update ca;
8            }
9        } catch (Exception e) {
10      
11              }
12    }
13}
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}