Salesforce : Update Contact for Person Account in Apex

By nature, Salesforce data model is designed for B2B instead of B2C. Most of the implementation we have done must have B2C enabled. A workaround to overcome this issue is to use Person Account. This feature is only available in the Enterprise edition. There are a few gotchas to know before you turn on this feature. In this blog, I will share one of my challenge while developing code against the Person Account.

 

Usually, we will query a Contact from Salesforce, synchronise it to another system and update the External ID. The code looks like this:

 

public void syncContact (Contact contact) {
  // Perform some logic to sync this contact into another external system
  ...
  ...
  // Once the synchronisation is complete, it may return an ID from this external system
  contact.External_ID__c = externalSystem.ID;
  update contact;
}

 

You will get an error as below:

 

INVALID_FIELD_FOR_INSERT_UPDATE, Account: bad field names on insert/update call:  AccountId: [ AccountId]

 

This error occur if you contact object has the AccountId field in the query. To overcome this, you can either remove this field from your query or use the following workaround:

 

public void syncContact (Contact contact) {
  // Perform some logic to sync this contact into another external system
  ...
  ...
  // Once the synchronisation is complete, it may return an ID from this external system
  // Create another contact object
  Contact newContact = new Contact(Id = contact.Id)
  newContact.External_ID__c = externalSystem.ID;
  update newContact;
}

 

 

Hope it helps!