What is the difference the methods used below in updating a list of records within an after update trigger context? The map variable just contains the opportunity ids that fired the trigger.
List<ServiceAppointment> servicelst = [select id,Status,Opportunity__c from ServiceAppointment where Status != 'Completed' and Status != 'Canceled' and opportunity__c in :opptyupdatemap.keyset()];
for(ServiceAppointment sa : servicelst) {
sa.Status = 'Cancelled';
}
if(!servicelst.isEmpty()) {
update servicelst;
}
and this approach:
List<ServiceAppointment> recordsToUpdate = new List<ServiceAppointment>();
List<ServiceAppointment> servicelst = [select id,Status,Opportunity__c from ServiceAppointment where Status != 'Completed' and Status != 'Canceled' and opportunity__c in :opptyupdatemap.keyset()];
for(ServiceAppointment sa : servicelst) {
sa.Status = 'Cancelled';
recordsToUpdate.add(sa)
}
if(!recordsToUpdate.isEmpty()) {
update recordsToUpdate;
}
The second approach creates a new list to store the updated record values where the first approach just updates the existing list record values that were changed in the loop without adding those updated records to a new list. I'm interested in understanding the difference between both patterns. I always create a new instance of a list to add updated record field values. I'm getting reports that the code is not always working and the Service Appointment records status value is not getting correctly updated. I'm wondering if it is possible the cause would be because the code uses the instance of the first list?