How to create a PersonAccount in salesforce using Apex code

I am trying to create a person account using the following code. Its throwing the following error: "Invalid constructor syntax, name=value pairs can only be used for SObjects". How to fix this.

Account Acc = new Account(FirstName='test1',LastName='test2',Email='');
insert acc;


 Id personAccountRecordTypeId =  Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('PersonAccount').getRecordTypeId();

Account newPersonAccount = new Account();

// for person accounts we can not update the Name field instead we have to update the    FirstName and LastName individually

 newPersonAccount.FirstName = 'Fred';
 newPersonAccount.LastName = 'Smith';
 newPersonAccount.RecordTypeId = personAccountRecordTypeId;
 insert newPersonAccount;

You will need to insert Account of RecordType of Person Account .Use developer name of record type as best practice.

If your code is in a Managed Package then you will get errors when you try to create a managed package because you cannot reference PersonAccount fields in a managed package. You will need to reference the fields dynamically to solve this.

The fields can be set like this:

newPersonAccount.put('FirstName', 'Fred');

Source : Link , Question Author : sunny , Answer Author : Mohith Shrivastava

Leave a Comment