Is the order of records in the Trigger.new list the same in before and after trigger?
Can I rely on the assumption that: on before r1 in the Trigger.new list on the 1st place; on after r1 in the Trigger.new list on the 1st place; Thanks
Is the order of records in the Trigger.new list the same in before and after trigger?
Can I rely on the assumption that: on before r1 in the Trigger.new list on the 1st place; on after r1 in the Trigger.new list on the 1st place; Thanks
No, you should not rely on the order of records in Trigger.new and Trigger.old. Use Trigger.newMap and Trigger.oldMap instead.
It's a better practice to use Trigger.newMap and Trigger.oldMap because you can't assume that directly querying the Trigger.new and Trigger.old lists will return the same number of records in the same order. Even though these lists are sorted by ID, external operations might change the number of records that are returned and make parallel list processing dangerous.
Source: http://developer.force.com/cookbook/recipe/comparing-queries-against-trigger-old-and-trigger-new
I would say yes since the triggers are associated with the list of records and not as a result of an actual database query. Similar to the database.saveresult where the records are returned in the same order as they are inserted.
I do not have any hard documentation on this but I would bet it is a good assumption..
In a trigger records are sorted by Salesforce Id.
So, In case of insert
you will get same order throughout the process. Also records insert in order they are inserted in list
so first record will get the least id and last one will get greatest Id.
I will not recommend to rely on that order. As it will require a complex design to function properly with different trigger event. However order will be same in after
and before
operations.
In addition to the other valuable remarks by other respondents, records in a before trigger that fail validation rules or otherwise have an addError()
method applied to them won't even appear in the after trigger's Trigger.new
variable. Thus, the size of the lists may not be equal, before vs after.