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
DevSFDevSF 

Update a checkbox on the latest record related to account.

Hi Friends,

I am writing a trigger on order object which updates a checkbox field on order based on the serial number.
I need to query all the orders related to an account and if the inserted order's serial number is the highest, then i have to update a checkbox__c on the order. If the latest order's serial number is lower than the existing one then it should be null.

This trigger should be fired while inserting or updating  an order.


This is my code. Please do make any changes and help me out.


trigger Updatelatestorder on Order (before insert,before update) {
    List<Order> orderlist = new List<Order>();
    List<Account> acclist = new List<Account>();
    set<Id> accountid = new Set<Id>();
    //orderlist = [select id, Status, checkbox_c, Accountid from Order Order by Serial_Number_c ASC];
    for(Order o : trigger.new){
      if(o.AccountId!= null){
             accountid.add(o.AccountId);
            }    
    }
 orderlist = [select id, Status, checkbox_c, Accountid from Order where Accountid In: accountid Order by Serial_Number_c ASC limit 1];
            for(Order oo :trigger.new){
                if(oo.Serial_Number_c!= null){
                    oo.checkbox_c = true;
                    orderlist.add(oo);
             }    
                if(orderlist.size()> 0){
                update orderlist;
            }
                }     




​Any Help would be appriciated....!
Apoorv Saxena 4Apoorv Saxena 4

Hi,


Please try the following code :

 

trigger Updatelatestorder on Order (before insert,before update) {
Set<Id> accIdSet = new Set<Id>();
Order ord = new Order();
    
    for(Order o : trigger.new){
        accIdSet.add(o.accountid);
    }
    
    try{
        ord = [Select id,Serial_Number_c,checkbox_c from Order where accountId in:accIdSet order by Serial_Number_c desc limit 1];
    } catch(Exception e){}
    
    for(Order o:trigger.new){
        if(ord<>null && ord.id<>null){
            if(o.Serial_Number_c>ord.Serial_Number_c){
                o.checkbox_c = true;
            } else {
                o.checkbox_c = false;
            }
        }
        else {
            o.checkbox_c =true; 
        }
    }
}


Please let me know if this helps !

Thanks,
Apoorv