Update related Account field on creating new Contact

You are currently viewing Update related Account field on creating new Contact
Update related Account on creating new contact

Scenario – We want to update selected Account field when new Contact is created.

Solution :

  1. Using Trigger
  2. Using Record Trigger Flow

In this article you will learn how to solve the given scenario using Trigger. You can also write Record Trigger flow for the same.

Create After Insert Trigger on Contact

				
					trigger ContactTrigger on Contact (after insert) {
    
    ContactTriggerHandler.updateAccount(Trigger.new);

}
				
			

Creating Trigger Handler

				
					public class ContactTriggerHandler {
    public static void updateAccount(List<Contact> record) {
        Contact contactRecord = [SELECT Account.Name from Contact where Id In: record];

        contactRecord.Account.Name = 'John Doe';
        update contactRecord.Account; 
    }
}
				
			

In the above code we are assuming that we have only record to process . Let’s see how to handle the same for bulk record.

Handling Bulk Records

				
					public static void updateAccount(List<Contact> records) {
        List<Contact> lstContact = [SELECT Account.Name from Contact where Id In: records];
        
        for(Contact con : lstContact) {
            con.Account.Name = 'Awasome';
            update con;
        }
}
				
			

This is how we can update related Account field when new Contact is created , you can use the same to update any related object records.

Leave a Reply