I have a requirement that only if the accounts list has one record, the inspectionsToUpdate is updated. If there is more than one record in the accounts list, for example, because someone is trying to mass update the business_launch_date__c field on multiple accounts via Data Loader, then an error is thrown both in data loader and in the debug logs. Right now, this is not working. With the below, if two accounts are in the data load, there is one success and one error, but the inspectionsToUpdate related lists for the success does not get updated. If you update the field on just one account, inspectionsToUpdate does work as expected. The way it should work is that if the accounts.size() > 1, then there are two errors, no successes. How do I fix this?
public static void afterUpdate(list<Account> newAccounts, map<Id, Account> oldMap) {
//1. When the Account field 'Business_Launch_Date__c' is set with a value, and previously it was null,
//Then update the field 'Test Inspection' to true on all related inspection records where Month Since Launch = 0
List<Account> accounts = [select name, id,Business_Launch_Date__c,
(select id,name,Month_Since_Launch__c,Test_Inspection__c, Inspection_Date__c
from Inspections__r
where Month_Since_Launch__c = 0)
from Account
where id In: newAccounts];
List<Inspection__c> inspectionsToUpdate = new List<Inspection__c>();
List<Inspection__c> testInspections = accounts[0].Inspections__r;
for(Account zee: newAccounts){
if(accounts.size() == 1){
if(zee.Business_Launch_Date__c != null){
if(oldMap.get(zee.id).Business_Launch_Date__c == null){
for(Inspection__c test: testInspections){
if(test.Test_Inspection__c == False && test.Inspection_Date__c < zee.Business_Launch_Date__c){
test.Test_Inspection__c = True;
inspectionsToUpdate.add(test);
}
}
}
}
update inspectionsToUpdate;
} else if(accounts.size() > 1 && zee.Business_Launch_Date__c != null && oldMap.get(zee.id).Business_Launch_Date__c == null){
for(Account accerrors: newAccounts){
Trigger.new[0].addError('You cannot update Business Launch Date in bulk.');
System.debug('The Business Launch Date cannot be updated in bulk. The following accounts were not updated: ' +accerrors);
}
}