Salesforce Apex Trigger – Child to Parent Trigger using Map

Salesforce Apex Trigger – Child to Parent Trigger using Map

Hello guys,

In this blog, I am sharing the code of trigger it will update the account field on updation or insertion of Contact field. Here, I am just updating the account field named Update_Checking__c whenever new value enters on contact field named Update_Checking__c.

For this, you need two custom field –

  1. Create custom field name as Update Checking in Account
  2. Create custom field name as Update Checking in Contact.

dont miss out iconDon’t forget to check out: Salesforce Apex Trigger – Parent to Child Trigger Using List

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;
}

Thanks.

Happy Coding!