Skip to content

Instantly share code, notes, and snippets.

@TheShubhamVsnv
Created June 30, 2021 12:45
Show Gist options
  • Save TheShubhamVsnv/3b0c5eb7d79555488c8abd365425d375 to your computer and use it in GitHub Desktop.
Save TheShubhamVsnv/3b0c5eb7d79555488c8abd365425d375 to your computer and use it in GitHub Desktop.
When a Billing Address is modified, get the new Postal Code. Then check which Contacts on the Account are outside that Postal Code. If 1 or more Contacts are outside of the Postal Code, mark Out_of_Zip as TRUE.
trigger TriggerExample on Account (before update, before insert) {
Set<Id> changedAccounts = new Set<Id>();
for(Integer i = 0; i < Trigger.New.size(); i++) {
Account newAcc = Trigger.New[i];
Account oldAcc = Trigger.Old[i];
if(newAcc.BillingStreet != oldAcc.BillingStreet ||
newAcc.BillingCity != oldAcc.BillingCity ||
newAcc.BillingState != oldAcc.BillingState ||
newAcc.BillingPostalCode != oldAcc.BillingPostalCode ||
newAcc.BillingCountry != oldAcc.BillingCountry)
changedAccounts.add(newAcc.Id);
Map<Id, Integer> accountsAndOutOfZips = new Map<Id, Integer>();
for(Contact c : [SELECT Id, Account.BillingPostalCode FROM Contact WHERE Id IN :changedAccounts]) {
if(c.MailingPostalCode != c.Account.BillingPostalCode) {
if(accountsAndOutOfZips.get(c.Id) == null)
accountsAndOutOfZips.put(c.Id, 1);
else
accountsAndOutOfZips.put(c.Id, accountsAndOutOfZips.get(c.Id) + 1);
}
}
for(Account acc : Trigger.New) {
if(accountsAndOutOfZips.get(acc.Id) != null && accountsAndOutOfZips.get(acc.Id) > 1)
acc.Out_of_Zip__c = true;
else
acc.Out_of_Zip__c = false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment