Development questions

When an Account's BillingCity is updated, update the MailingCity on all its related Contacts.

DevelopmentEasyTCSWiproCapgemini

Use after update on Account, filter accounts whose BillingCity changed, then query and update their Contacts.

apex
trigger AccountTrigger on Account (after update) {
    Map<Id, String> cityByAcc = new Map<Id, String>();
    for (Account a : Trigger.new) {
        if (a.BillingCity != Trigger.oldMap.get(a.Id).BillingCity) cityByAcc.put(a.Id, a.BillingCity);
    }
    if (cityByAcc.isEmpty()) return;
    List<Contact> cons = [SELECT Id, AccountId FROM Contact WHERE AccountId IN :cityByAcc.keySet()];
    for (Contact c : cons) c.MailingCity = cityByAcc.get(c.AccountId);
    update cons;
}
apex-triggertriggercodingscenario