1

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"
    }
  }
  • Please see below code snippet to solve your problem and mark it answer if it resolves your issue. – SFDC Learner Dec 17 '18 at 5:43
1

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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.