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 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 records) {
List 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.