0

I'm aware that Salesforce provides a native way to use country and state values in Account and Contact address fields. But what if I want to use apex to get those list of countries so that I can use them in a custom LWC? Is there a way?

(I tried this, but I'm not sure the data structure matches my environment, as it's looking for a "MailingCountry" field in the Contact object, but that doesn't exist).

3 Answers 3

2

The MailingAddress and ShippingAddress fields are special compound fields. They're read-only, and hide the fact that there are indeed separate fields backing them.

So while you won't find MailingCountry explicitly listed as a field on the Account or Contact object, the field does in fact exist.

This information is also corroborated by the SOAP API documentation for Contact (you'll find MailingAddress, followed by MailingCity, MailingState, etc...)

2

As Derek mentioned, MailingCountry is part of the MailingAddress compound field on the Contact object. So it should exist.

Another possible explanation for your issue is that you don't have State and Country/Territory Picklists enabled in your org.

Once you have that enabled, the first block of code in the blog entry you linked should work, although it's more verbose than it needs to be. The 2nd block of code is incorrect (You can't just instantiate a List in Apex, it has to be a list of something specific. Also, you do need to use MailingCountryCode instead of MailingCountry in this case.)

I enabled State and Country/Territory Picklists in my dev org. After that, the following code worked for me in Execute Anonymous:

List<Schema.PicklistEntry> values = Contact.MailingCountryCode
  .getDescribe()
  .getPickListValues();
List<SelectOption> options = new List<SelectOption>();
for (Schema.PicklistEntry v : values) {
    options.add(new SelectOption(v.getLabel(), v.getLabel()));
}
System.debug(options);
-3
public static List <String> getBillingCountry(){
        List<String> pickListValuesList= new List<String>();
        Schema.DescribeFieldResult fieldResult = Account.BillingCountry.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        for( Schema.PicklistEntry pickListVal : ple){
            pickListValuesList.add(pickListVal.getLabel());
        }     
        return pickListValuesList;
    }
1
  • This appears to be the same as Matthew Souther's answer from 2.5 years ago, just with less information.
    – Derek F
    Apr 22 at 11:39

You must log in to answer this question.

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