html code

How can we know State and Country Picklist is enabled or not in an org using Apex Code

Question

How can we know State and Country Picklist is enabled in the Salesforce org or not using Apex code

SOLUTION

When you enable that feature SFDC creates a countryCode field for each object where the address exists. Then you could check if that field exist using something like this:

system.debug(Account.getSobjectType().getDescribe().fields.getMap().keySet().contains('countryCode'));




Other generic option:

*
* check if an Sobject has a field
*/
public static boolean hasSObjectField(String fieldName, SObject so){
   String s = JSON.serialize(so);
   // Deserialize it back into a key/value map
   Map<String, Object> obj = (Map<String, Object>) JSON.deserializeUntyped(s);


   // Build a set containing the fields present on our SObject
   Set<String> fieldsPresent = obj.keyset().clone();
   return fieldsPresent.contains(fieldName);
}


Account a = new Account(name='Test');
System.debug(hasSObjectField('BillingCountryCode', a));