html code

Salesforce Apex Trigger – Implementing a Child-to-Parent Trigger Using a Map

Hello everyone,

In this blog post, I’m sharing a trigger code that updates the “Update_Checking__c” field in the Account object when a Contact field is updated or inserted. I’m specifically updating the “Update_Checking__c” field in the Account object whenever a new value is added to the Contact field with the same name, “Update_Checking__c.”

To implement this, you’ll need to create two custom fields:

  1. Create a custom field named “Update Checking” in the Account object.
  2. Create a custom field named “Update Checking” in the Contact object.
trigger UpdateFieldInAccount on Contact (after insert, after update) { 
    Map<Id,String> accountIdwithContactField = new Map<Id, String>(); 
    for(Contact con:trigger.new) {
        accountIdwithContactField.put(con.AccountId, con.Update_Checking__c);
    } 
    List<Account> listUpdatedAccount = new List<Account>(); 
    for(Account acc:[Select id, Update_Checking__c From Account Where Id IN :accountIdwithContactField.Keyset()]) {
        if(accountIdwithContactField.containsKey(acc.id)) {
            listUpdatedAccount.add(new Account(Id = acc.id, Update_Checking__c=accountIdwithContactField.get(acc.id)));
        }
    }
    update listUpdatedAccount;
}

Thank you.

Wishing you productive coding!