Newer Version Available

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

Apex Trigger: Prevent Closure of Work Orders with Open Line Items

The following trigger prevents users from closing a work order unless all its line items have been closed. It’s a good way to ensure that all scheduled tasks are completed. The accompanying unit test scans your code for issues.
To define a work order trigger in your org:
  1. In Lightning Experience, select Work Order in the Object Manager in Setup, then click Triggers. In Salesforce Classic, enter Work Orders in the Quick Find box in Setup, then click Triggers under Work Orders.
  2. Click New.
  3. Copy the trigger text and paste it into the text field.
  4. Click Save.
1trigger ValidateWorkOrderLineItem on WorkOrder (before update) {
2  // Create a map of work order Id to workorders where status is closed
3  Map<String, WorkOrder> mapWoToId = new Map<String,WorkOrder>();
4  for(WorkOrder w : Trigger.New) {
5    if(w.Status =='Closed'){
6      mapWoToId.put(w.Id, w);
7    }
8  }
9  
10  // Select the work order line items which are not closed for the list of work orders
11  List<WorkOrderLineItem> woLineItemList = [select woli.Status, woli.workOrderId
12                        from WorkOrderLineItem woli 
13                        where woli.WorkOrderId IN :mapWoToId.keySet() and woli.Status != 'Closed']; 
14
15  // Set tje error message for the parent work order	
16  for(WorkOrderLineItem woli : woLineItemList) {
17      WorkOrder parentWO = mapWoToId.get(woli.workOrderId);
18      parentWO.addError('You cannot close a work order until all of its line items are closed.');\
19  } 
20}