0

I have made a new trigger on Accounts and have a made a custom field on accounts name Contact ID. So whenever a person account is created it should populate the Contact ID field on person account. The trigger is working fine for this, but now i want the same trigger for before update for the existing accounts we do a mass update on person account it should have the Contact ID populated.Please help and explain the process here:

    trigger UpdateContactID on Account (after insert, before update) 
    {
     List<String> newAccountIDList = new List<String>();
       if (trigger.isinsert){
     // Taking all account IDs in collection
        for(Account acct: Trigger.new)
        {  
      newAccountIDList.add(acct.ID); 
         }
      // Fetching contacts against the account IDs
        List<Contact> contactList = [SELECT Id, Account.Id FROM Contact WHERE Account.ID in :newAccountIDList];      
      // Adding contacts in a map with relation to Account ID
       Map<String, Contact> mapContact = new Map<String, Contact>();
       for(Contact cont : contactList)
        {
          mapContact.put(cont.Account.Id, cont) ;
         }
        // Updating Contact_ID__c from Map to new Account list to update
         List<Account> newAccounts = [select Id, Contact_ID__c from Account where Id in :newAccountIDList];
         List<Account> toUpdate = new List<Account>();
         for(Account acct: newAccounts)
         {  
          toUpdate.add(new Account(id = acct.Id,Contact_ID__c =    mapContact.get(acct.Id).Id
          ));
         }
     update toUpdate;
      }
}

1 Answer 1

1

Jovi,

If you are using Person Accounts, you will find a standard field called PersonContactId which will give you the Contact Id associated with that Account.

You don't need a separate custom field and a trigger to populate the field.

You can also refer this page for additional guidance on using Person Accounts.

2
  • Due to some reason i cant find the field Person Contact ID? Please explain
    – Jovi
    Mar 16, 2015 at 3:19
  • did you try running a SOQL query like Select Id, PersonContactId from Account where Id='UseAnyOfYourAccountIdHere' Mar 16, 2015 at 3:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .