When state/country picklists are enabled, in an apex class can i find whether the state code is related to the country code.

Currently if no check is done.

I'm getting the below error in the visual force page.

Invalid State Code 
Invalid state specified for field  

Can we handle such type of errors. I have tried by making the below code changes but no use.

Contact myContact = new Contact();
myContact.MailingCountryCode = 'US';
    myContact.MailingStateCode = 'NL';
}catch(Exception e){
 ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'No Relation'));

Is there any way to find whether the state code is related to a country code.

Thanks in advance

  • You may find the answer to how to parse dependent picklists here: salesforce.stackexchange.com/questions/4462/…
    – Adrian Larson
    Sep 26 '16 at 14:27
  • @AdrianLarson, Thanks. Can this be used for the Contact MailingCountryCode and MailingStateCode. Sep 26 '16 at 16:46
  • It should...I haven't the time to try it for you, but I recommend you take a stab at it and come back if you face any specific issues.
    – Adrian Larson
    Sep 26 '16 at 16:49
  • 3
    I think the whole point of state and country picklists is to prevent entry of invalid data and hence apex shouldn't be needed. Note that the more important info might be that if you don't enable states for country X, you simply can't enter a state for country X. Any value entered is going to be flagged by SFDC as invalid
    – cropredy
    Sep 26 '16 at 16:59
  • To handle this scenario we should either create our own dependent picklists of CountryCodes and StateCodes or we could either use a third party State/Country library to get this done. Feb 15 '17 at 12:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.