5

How to know State and Country Picklist is enabled in an org or not using Apex Class when working on an app and there may be any org where This picklist is enable or not enable?

Thanks!

2 Answers 2

5

When you enabled that feature SFDC create a countryCode field for each object where 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));

I posted time ago that function here

8
  • Serialize and Deserialize will take some time i guess ?So i still Prefer the one below .. Commented Mar 26, 2014 at 12:03
  • You are right about the overtime to serialize/deserialize the SObject, I updated my answer Commented Mar 26, 2014 at 12:09
  • 2
    I thought that Account metadata description is in cache on execution context. But probably you are right on throw/catch an exception is faster than describe method. Commented Mar 26, 2014 at 14:01
  • 4
    I agree, the best approach here is to use Account.getSobjectType().getDescribe().fields.getMap(). Using the serialisation or catching exceptions is more indirect. If you do the check in a static constructor it will only go off once anyway, depending on the overall length of the request the % of time taken for either solution is likely not that significant, though I'd still go via Apex Describe. As it happens this is what I did for this answer as well. gist.github.com/afawcett/9345047#file-address-cls-L9 Commented Mar 26, 2014 at 18:34
  • 1
    @AndrewFawcett Thanks! This is what i'm looking for.
    – Tepsi
    Commented Mar 28, 2014 at 6:10
3

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

Using the above model for this question as well

public Boolean CountryPicklistEnabled(){
try{
    // Try to use the BillingCountryCode field.
    sObject testObject = new Account();
    testObject.get( 'BillingCountryCode' );
    // If we got here without an exception, return true.
    return true;
}
catch( Exception ex ){
    // An exception was generated trying to access the BillingCountryCode field
    return false;
 }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .