Loading

Access the state and country picklist through Apex

Publiceringsdatum: May 3, 2026
Beskrivning

Salesforce allows administrators to enable State and Country/Territory picklists to standardize address data entry across the org. Once enabled, these picklists can be accessed programmatically via Apex using the Schema.DescribeFieldResult class. This article provides sample Apex code to retrieve all country codes and state codes currently available in your Salesforce org, which can be used for custom validation, integration field mapping, or dynamic UI population.

Lösning

Before running the sample code below, ensure that State and Country/Territory Picklists are enabled in your Salesforce org. Navigate to the following path to enable them and complete all required steps.


Makes sure the state and country picklist is enabled in the ORG.

  • For Lightning UI : "Setup | Data | State and Country/Territory Picklists | Complete all the steps" 
  • For Classic: "Setup | Data Management | State and Country/Territory Picklists | Complete all the steps "
  • Find below the link that has steps to enable the state and country pick list in the ORG. 

 

1. Sample 1: Retrieve all country codes

The following Apex code uses Schema.DescribeFieldResult on the User.Countrycode field to retrieve all enabled country picklist entries. It logs each entry's label (display name) and value (ISO country code) to the Developer Console debug log. Run this in the Developer Console using Execute Anonymous.
Schema.DescribeFieldResult fieldResult = User.Countrycode.getDescribe();
List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
System.debug('Picklist::'+ple);
for( Schema.PicklistEntry f : ple){
System.debug(f.getLabel() +'::'+ f.getValue());
}

2. Sample 2: Retrieve all state codes

The following code retrieves all state and territory codes across all countries enabled in the picklist. Results include states from all enabled countries. Additional filtering logic is required if you need states for a specific country only.
Schema.DescribeFieldResult fieldResult = User.statecode.getDescribe();
List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
System.debug('Picklist::'+ple);
for( Schema.PicklistEntry f : ple){
System.debug(f.getLabel() +'::'+ f.getValue());
}


Important: The code samples above return all available picklist entries for the country and state fields respectively. To filter by a specific country, or to retrieve state values for a particular country code only, additional filtering logic is required. These samples serve as a starting point and must be adapted to meet your specific business requirements.

Knowledge-artikelnummer

000387645

 
Laddar
Salesforce Help | Article