Find your content:

Search form

You are here

What's the best way to check if person accounts are enabled via Apex Code?

 
Share

I need to be able to check if an org has Person Accounts enabled via Apex Code as part of package. What's the best way to do this without making the package require Person Accounts be enabled in any org in which it's installed?


Attribution to: E.J. Wilburn

Possible Suggestion/Solution #1

Method 1

Try to access the isPersonAccount property on an Account and catch any exception that occurs if that property is missing. If an exception is generated then person accounts are disabled. Otherwise they're enabled. To avoid making person accounts required for the package you assign the Account object to an sObject and use sObject.get( 'isPersonAccount' ) rather than accessing that property directly on the Account object.

This method takes ~3.5ms and negligible heap space in my testing.

// Test to see if person accounts are enabled.
public Boolean personAccountsEnabled()
{
    try
    {
        // Try to use the isPersonAccount field.
        sObject testObject = new Account();
        testObject.get( 'isPersonAccount' );
        // If we got here without an exception, return true.
        return true;
    }
    catch( Exception ex )
    {
        // An exception was generated trying to access the isPersonAccount field
        // so person accounts aren't enabled; return false.
        return false;
    }
}

Method 2

Use the account meta-data to check to see if the isPersonAccount field exists. I think this is a more elegant method but it executes a describe call which counts towards your governor limits. It's also slightly slower and uses a lot more heap space.

This method takes ~7ms and ~100KB of heap space in my testing.

// Check to see if person accounts are enabled.
public Boolean personAccountsEnabled()
{
    // Describe the Account object to get a map of all fields
    // then check to see if the map contains the field 'isPersonAccount'
    return Schema.sObjectType.Account.fields.getMap().containsKey( 'isPersonAccount' );
}

Attribution to: E.J. Wilburn
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/1055

My Block Status

My Block Content