function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Brandon WermesBrandon Wermes 

Help bulkifying trigger on child object

Let me preface this post by saying that I am very new to Apex and somewhat need to OOP, so my apologies if this is a complete rookie post.

I am working on a trigger surrounding Work Orders (parent) and Work Order Line Items (child). Specifically, I want the status of the Work Order to change from it's current status to "Completed" once all Work Order Line Items on the Work Order are status = "Completed".

To accomplish this, I am counting the total number of Work Order Line Items on that Work Order, then I am counting the number of Work Order Line Items that have a status of "Completed". If the numbers match, I am performing the edit on the Work Order.
Code:
trigger WorkOrderLinesComplete on WorkOrderLineItem (after update) {
    for(WorkOrderLineItem woli : trigger.new){
        if (woli.Status == 'Completed'){
            integer completedCount = [Select count() from workorderlineitem where WorkOrderId = :woli.WorkOrderId and Status = 'Completed'];
            integer totalCount = [Select count() from workorderlineitem where WorkOrderId = :woli.WorkOrderId];
            if (completedCount == totalCount){
                WorkOrder wo = [Select id,status from WorkOrder where id = :woli.WorkOrderId];
                if (wo.Status != 'Completed'){
                    wo.status = 'Completed';
                    update wo;
                }
            }
        }
    }
}

Please let me know if this is acceptable, and if not any suggestions on improving.

Thanks as always!
Best Answer chosen by Brandon Wermes
Suraj TripathiSuraj Tripathi

Hi Brandon,

Your trigger is correct, few suggestion for the best practices of the trigger :

1.  Avoid doing the code inside the trigger.
2. Always use context trigger Like :

trigger WorkOrderLinesComplete on WorkOrderLineItem (after update) {
if(trigger.isafter && trigger.isupdate){
  classname.methodname(trigger.new);
}
}
3. Avoid DML inside for Loop.

For More info Link: https://developer.salesforce.com/page/Apex_Code_Best_Practices

Hope it Helps you. Mark this answer Solved if it resolves your query.​

Regards,
Suraj