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 

Trigger to update a checkbox on latest child record.

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....!
Nayana KNayana K
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>();
	// Assuming serial number is integer
    Map<Id, Integer> mapAccIdToMaxSerNum = new Map<Id, Integer>();
    for(Order o : trigger.new){
      if(o.AccountId != null){
             accountid.add(o.AccountId);
            }    
    }

	for (AggregateResult ar : [SELECT AccountId, MAX(Serial_Number_c)
		  FROM Order
		  GROUP BY AccountId])  {
		  mapAccIdToMaxSerNum.put((Id)ar.get('AccountId'), Integer.valueOf(ar.get('expr0')));
    
		}

	for(Order oo :trigger.new){
		if(mapAccIdToMaxSerNum.containsKey(oo.AccountId) && oo.Serial_Number_c > mapAccIdToMaxSerNum.get(oo.AccountId))
		{
			oo.checkbox_c = TRUE;
		}
		else
		{
			oo.checkbox_c = FALSE;
		}
	 }     
}

I am not sure whether above code is helpfull but you can give a try.
DevSFDevSF
Hi Nayana,

Thanks alot for your response. The code you have sent is working. I need an update in the code.

Like you are making the checkbox true for latest serial number. And the previous records checkbox should be unchecked.
i mean previous record related to this account which has lower serial number than this new record should be unchecked.
As this is a task which needs to be done on priority. Execting a sooner response.

Please update the code for this.. 
It Means alot if can sought this out. :)

Thanks,
Nayana KNayana K
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>();
	Set<Id> setAccId = new Set<Id>();
	Set<Id> setOrderId = new Set<Id>();
	// Assuming serial number is integer
    Map<Id, Integer> mapAccIdToMaxSerNum = new Map<Id, Integer>();
    for(Order o : trigger.new){
      if(o.AccountId != null){
             accountid.add(o.AccountId);
            }    
    }

	for (AggregateResult ar : [SELECT AccountId, MAX(Serial_Number_c)
		  FROM Order
		  GROUP BY AccountId])  {
		  mapAccIdToMaxSerNum.put((Id)ar.get('AccountId'), Integer.valueOf(ar.get('expr0')));
    
		}

	for(Order oo :trigger.new){
		if(mapAccIdToMaxSerNum.containsKey(oo.AccountId) && oo.Serial_Number_c > mapAccIdToMaxSerNum.get(oo.AccountId))
		{
			oo.checkbox_c = TRUE;
			setAccId.add(oo.AccountId);
			if(oo.Id != null)
				setOrderId.add(oo.Id);
		}
		else
		{
			oo.checkbox_c = FALSE;
		}
	 }   
		List<Order> lstOrderToUpdate = new List<Order>();
		for(Order objExistingOrder : [select id, checkbox_c, Accountid from Order where Accountid In: setAccId AND Id NOT IN: setOrderId]){
			objExistingOrder.checkbox_c = FALSE;
			lstOrderToUpdate.add(objExistingOrder);
		}
		
		if(!lstOrderToUpdate.isEmpty())
			update lstOrderToUpdate;
}

Try this once.
DevSFDevSF
Thank you very much for your quick response.

Yes, it;s working. But since i deployed it to production. Getting this error frequently and i was never aware of it.
Could you please look into it. 


Error:


Errors: [[{"message":"Updatelatestorder: execution of BeforeInsert\n\ncaused by: System.QueryException: Non-selective query against large object type (more than 200000 rows). Consider an indexed filter or contact salesforce.com about custom indexing.\nEven if a field is indexed a filter might still not be selective when:\n1. The filter value includes null (for instance binding with a list that contains null)\n2. Data skew exists whereby the number of matching rows is very large (for instance, filtering for a particular foreign key value that occurs many times)\n\nTrigger.Updatelatestorder: line 15, column 1","statusCode":"CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY"}]]


Appriciate your response once again :)

Thanks,
Dev
DevSFDevSF
Thank you very much for your quick response.

Yes, it;s working. But since i deployed it to production. Getting this error frequently and i was never aware of it.
Could you please look into it. 


Error:


Errors: [[{"message":"Updatelatestorder: execution of BeforeInsert\n\ncaused by: System.QueryException: Non-selective query against large object type (more than 200000 rows). Consider an indexed filter or contact salesforce.com about custom indexing.\nEven if a field is indexed a filter might still not be selective when:\n1. The filter value includes null (for instance binding with a list that contains null)\n2. Data skew exists whereby the number of matching rows is very large (for instance, filtering for a particular foreign key value that occurs many times)\n\nTrigger.Updatelatestorder: line 15, column 1","statusCode":"CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY"}]]


Appriciate your response once again :)

Thanks,
Dev
Nayana KNayana K
for (AggregateResult ar : [SELECT AccountId, MAX(Serial_Number_c)
		  FROM Order
WHERE AccountId IN: accountid
GROUP BY AccountId])  {
		  mapAccIdToMaxSerNum.put((Id)ar.get('AccountId'), Integer.valueOf(ar.get('expr0')));
    
		}

Sorry I had missed to add filter..paste above code