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!
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
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;
}
}