The following code is called by an after update
trigger on Account
. It finds all an account's children Account_Configuration__c
records (child name for SOQL is Customer_Credentials__r
) and -- if the account's Satisfaction_Comments__c
field is updated -- it updates all those Account_Configuration__c
records' Satisfaction_Comments__c
fields.
Now, it doesn't just update the field to be the same as the account's. Rather, the code takes an Account_Configuration__c record's Satisfaction_Comments__c field (Long Text Area) and adds the account's value to what's already there. The final result for that field is a series of the following: Date the account Satisfaction Comment was made appended to the actual value of that field, each on its own line.
The code works, but it involves a for loop in a for loop. Is it possible to remove that nesting?
Here's the code:
public void updateProdImpsWithAccHis(Account[] updatedAccounts, Map<Id, Account> AccountOldMap) {
set<Id> accIds = new Set<Id>();
for(Account updatedAccount : updatedAccounts){
accIds.add(updatedAccount.Id);
}
List<Account> accList = [SELECT Id,Satisfaction_Comments__c,Acct_Sat_Comments_Date__c,LastModifiedDate,(SELECT Id,Satisfaction_Comments__c FROM Customer_Credentials__r) FROM Account WHERE Id IN :accIds];
List<Account_Configuration__c> prodImpUpdates = new List<Account_Configuration__c>();
for(Account acc : accList){
if(acc.Satisfaction_Comments__c != AccountOldMap.get(acc.Id).Satisfaction_Comments__c){
for(Account_Configuration__c pi: acc.Customer_Credentials__r) {
if(pi.Satisfaction_Comments__c == null){
pi.Satisfaction_Comments__c = (acc.LastModifiedDate).addHours(-5) + ': ' + acc.Satisfaction_Comments__c;
} else {
pi.Satisfaction_Comments__c = (acc.LastModifiedDate).addHours(-5) + ': ' + acc.Satisfaction_Comments__c + '\n' + pi.Satisfaction_Comments__c;
}
prodImpUpdates.add(pi);
}
}
}
if(!prodImpUpdates.isEmpty()){
update prodImpUpdates;
}
}
if
's and some assignments. If you're really worried, try stress testing it with a huge amount of records, but honestly, it's unlikely you'll figure out a more effective way to set values on child records of an object. Could be worth setting up a formula field or a workflow to provide the text formatting, instead of writing your own code tho.if(!prodImpUpdates.isEmpty()){ update prodImpUpdates; }
is the same asupdate prodImpUpdates;
, but requires more code and CPU time.