[SalesForce] How to set ParentID field on Account record related to contact in a Trigger

I have a trigger that is firing on before insert on the Contact object. I am trying to set the parent ID field on the Account record that the Contact is associated with.

I can't seem to access the related account through the contact in Trigger.New. My trigger calls method in a class which is shown below.

What code is needed to set the parentID field of the Account associated with each possible contact record that gets passed into this method?

 public static void setParentAccount(List<Contact> contacts) {

    Set<String> domains = new Set<String>();

    for(Contact record: contacts) {
      if(record.email != null) {
       domains.add(record.email.split('@')[1]);
      }
    }

   Map<String, Id> accountsByDomain = new Map<String, Id>();

   for(Account record: [select account_domain__c from account where account_domain__c = :domains]) {
     accountsByDomain.put(record.account_domain__c, record.Id);
   }
  }

  for(Contact record: contacts) {
    if(record.email != null) {
      // the ID of the parent account I want to set on the related Account of this contact
      Id accountId = accountsByDomain.get(record.email.split('@')[1]);

     //  **** Here I want to set the parentId field on the associated account equal to "accountId"
    }
  }

Best Answer

You are getting the AccountId from accountsByDomain map which you want to set on the Contact's Account ParentId. Please see below code to achieve this.

Take one list of Account which we will use to update the Contact's Account.

List<Account> lstAccount = new List<Account>();
for(Contact record: contacts) {
   if(record.email != null) {
      // the ID of the parent account I want to set on the related Account of this contact
      Id accountId = accountsByDomain.get(record.email.split('@')[1]);
      if(record.AccountId != null)
          lstAccount.add(new Account(Id = record.AccountId, ParentId = accountId));
    }
}
update lstAccount;