[SalesForce] How to convert Business Account to Person Account? It is giving me an Error

trigger BusinessToPerson on Account (after update) {
private static RecordType SeekerPersonAccount = [SELECT id FROM RecordType WHERE DeveloperName = 'PersonAccount' and sObjectType = 'Account' and isActive = true limit 1];
        List<Account> accountList = new List<Account>();
        for (Account newAccount : Trigger.new){
            if (newAccount.Name == 'ConvertMe'){
                Account a = new Account();
                a.Id = newAccount.Id;
                a.RecordTypeId = SeekerPersonAccount.id;
                accountList.add(a);
            }
        }

        if(accountList != null && accountList.size() > 0){
            update accountList;
        }
}

Error:Apex trigger BusinessToPerson caused an unexpected exception, contact your administrator: BusinessToPerson: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 0017F00000UyUhUQAV; first error: INVALID_PERSON_ACCOUNT_OPERATION, account cannot be converted to person-account: []: Trigger.BusinessToPerson: line 14, column 1

Best Answer

In order to convert a business account to a person account, it must meet certain requirements. This includes already having exactly one contact on the account. You may wish to modify your trigger to check the requirements beforehand. A slightly modified version of your trigger works in my org:

trigger PersonAccount on Account (after update) {
    RecordType pa = [SELECT Id FROM RecordType WHERE IsPersonType = true LIMIT 1];
    Set<Id> hasContacts = new Map<Id, AggregateResult>([
      SELECT AccountId Id, COUNT(Id) FROM Contact
      GROUP BY AccountId
      HAVING COUNT(Id) = 1
    ]).keySet();
    Account[] updates = new Account[0];
    for(Account record: Trigger.new) {
        if(hasContacts.contains(record.Id) && record.RecordTypeId != pa.Id && record.Name == 'ConvertMe') {
            updates.add(new Account(Id=record.Id, RecordTypeId=pa.Id));
        }
    }
    update updates;
}

Note also that you should check if it is already a person account before converting (as demonstrated above).

Related Topic