Need some assistance in modifying my Trigger. My trigger works for every status changed in Orders. But since there are lots of Orders in every Case, I want the trigger to update the Case Status only when ALL Orders records related to that Case have Approved Status. Only then the Case should update to “Completed” Status. Thanks in advance.

trigger OrderTrigger on Order (after insert, after update) {

    Set<Id> caseIds = new Set<Id>();
    for (Order Ord:Trigger.new) {

    Map<Id, Case> caseMap = new Map<Id, Case>([SELECT Id, Status FROM Case WHERE Id IN :caseIds]);
    List<Case> CaseList = new List<Case>();

    String caseApproved = 'Approved';
    String caseCompleted = 'Completed';
    String caseInvalid = 'Invalid';
    String caseRejected = 'Rejected';
    String caseNew = 'New';
    String caseIncomplete = 'Incomplete';
    String caseInProgress = 'In-Progress';

    //For insert and update trigger
    if(Trigger.isInsert || Trigger.isUpdate){
        for (Order currentOrd:Trigger.new) {
            Case ordCase = caseMap.get(currentOrd.Case__c);

            if(currentOrd.Status == caseApproved) {
                ordCase.Status = caseCompleted;
            if(currentOrd.Status == caseInvalid) {
                ordCase.Status = caseRejected;
            if(currentOrd.Status == caseNew || currentOrd.Status == caseIncomplete) {
                ordCase.Status = caseInProgress;

    update CaseList;
  • Do you want to update case based on all orders to Approved status only? Or is this applicable for other statuses as well? – Reshma Jan 7 '19 at 6:44
  • I want the trigger to update the Case Status if all Order records have "Approved" Status. Let say there are 4 Order records in a Case, if all 4 Order records have Approved Status, then the Case Status should change to "Completed". But if only one Order records change to Approved, the other 3 are still not approved, the trigger didn't update the Case Status. thanks sir – vlink Jan 7 '19 at 6:56

You may need an Integer variable to count the approved orders and and total orders on a Case to check whether all the orders are approved or not. Also ensure correct API name for child orders. I just put Orders__r for now. Try below code and check.

List<Case> CaseList = new List<Case>();
Integer countApproved = 0;
for(Case c :[SELECT Id, Status, (SELECT Id, Status FROM Orders__r) FROM Case WHERE Id IN :caseIds]){
    for(Oreder o :c.Orders__r){
        if(o.Status == caseApproved){
            countApproved = countApproved + 1;
    if(c.Orders__r.size() == countApproved){
         c.Status = caseApproved;
update CaseList;
|improve this answer|||||
  • @vlink Did you give a try? – Reshma Jan 10 '19 at 6:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.