Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save charltonAthletic/0b04cafd87c3ace5f8ce to your computer and use it in GitHub Desktop.
Save charltonAthletic/0b04cafd87c3ace5f8ce to your computer and use it in GitHub Desktop.
//A common pattern for triggered operations in Apex
public static void updateContactPhone (List<Account> priorAccounts, List<Account> updatedAccounts) { // static method, takes 2 List params of Account sObject type
Set<Id> modifiedAccounts_Ids = new Set<Id>();
for (Integer i=0; i<updatedAccounts.size(); i++) { // Array notation - Alternative is... for (Account a : updatedAccounts) {
if (updatedAccounts[i].Phone != priorAccounts[i].Phone) { // if the phone number is different... (use dot notation to get to field value)
modifiedAccounts_Ids.add(updatedAccounts[i].Id); // add the Account Id to the List collection
}
}
if (modifiedAccounts_Ids.size() > 0) { // typical control flow
List<Contact> contactQuery = [SELECT Id, Phone, AccountId, Account.Phone FROM Contact WHERE AccountId IN :modifiedAccounts_Ids
LIMIT : (limits.getLimitQueryRows()-limits.getQueryRows())]; // Limits method means we never exceed the limit
List<Contact> contactUpdates = new List<Contact>();
for (Contact c : contactQuery) {
// limit to just the records that need it
if (c.Phone != c.Account.Phone && contactUpdates.size() < limits.getLimitDMLRows()) {
c.Phone = c.Account.Phone;
contactUpdates.add(c);
}
}
if ( contactUpdates.size() > 0 ){ // typical control flow
update contactUpdates;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment