Accessing a Name field of Business Acct in a trigger causes "Invalid field Name for Account" error when inserting a list of Accts mixed w/ Person Acct
Last updated 2016-07-28 ·Reference W-1978779 ·Reported By 15 users
No Fix
Summary
Accessing a value of the Name field of Business Account through the sObject.get() Apex method in a trigger on Account can cause the "System.SObjectException: Invalid field Name for Account" error when inserting a list of Account which includes both of Person Account and Business Account.
Repro
1. Enable Person Account
2. Define a trigger which accesses a Name field of Business Account.
//////////////////////////////////////////////////////////////////////////
trigger MyAccountTrigger on Account (before insert) {
for (Account acc : Trigger.new) {
if (!acc.isPersonAccount) {
System.debug('Name: ' + acc.get('Name'));
}
}
}
//////////////////////////////////////////////////////////////////////////
3. Execute the following apex code through devconsole or workbench
//////////////////////////////////////////////////////////////////////////
List<Account> accs = new List<Account>();
ID personRecId = [select id from recordtype where name = 'Person Account'].id;
accs.add(new Account(recordTypeId = personRecId, lastName = 'Person1'));
ID businessRecId = [select id from recordtype where name != 'Person Account' and sobjecttype = 'Account' limit 1].id;
accs.add(new Account(recordTypeId = businessRecId, Name = 'Business1'));
insert accs;
//////////////////////////////////////////////////////////////////////////
You will see the following error:
EXCEPTION: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, MyAccountTrigger: execution of BeforeInsert caused by: System.SObjectException: Invalid field Name for Account
Workaround
Reverse the order of insertion where business account is followed by person account. You will not see the error anymore.
//////////////////////////////////////////////////////////////////////////
List<Account> accs = new List<Account>();
ID businessRecId = [select id from recordtype where name != 'Person Account' and sobjecttype = 'Account' limit 1].id;
accs.add(new Account(recordTypeId = businessRecId, Name = 'Business1'));
ID personRecId = [select id from recordtype where name = 'Person Account'].id;
accs.add(new Account(recordTypeId = personRecId, lastName = 'Person1'));
insert accs;
//////////////////////////////////////////////////////////////////////////
Is it Fixed?
Any unreleased services, features, statuses, or dates referenced in this or other public statements are not currently available and may not be delivered on time or at all. Customers who purchase our services should make their purchase decisions based upon features that are currently available.