mar 242015

Salesforce – How to access State and Country Picklists values in Apex?

Salesforce provides a native way to use country and state values in Account and Contact address fields. It’s very useful on page layouts. But what if we want access that values and use them in our Apex Class and Visualforce Page?

Here is a sample code retrieve those values and use Map to store them.

Map<String,String> maplabelVal=new Map<String,String>();
// Get the object type of the SObject.
Schema.sObjectType objType = Contact.getSObjectType();
// Describe the SObject using its object type.
Schema.DescribeSObjectResult objDescribe = objType.getDescribe();
// Get a map of fields for the SObject
map<String, Schema.SObjectField> fieldMap = objDescribe.fields.getMap();
// Get the list of picklist values for this field.
list<Schema.PicklistEntry> values = fieldMap.get('MailingCountryCode').getDescribe().getPickListValues();
// Add these values to the selectoption list.
for (Schema.PicklistEntry a : values){
   maplabelVal.put(a.getLabel(), a.getValue());
}
system.debug('MAP: '+maplabelVal);
system.debug('ISO CODE: '+maplabelVal.get('Andorra'));

 

And here is the sample Apex code to use it later in VF Page:

public List<SelectOption> getCountries()
{
  Schema.sObjectType objType = Contact.getSObjectType();
  Schema.DescribeSObjectResult objDescribe = objType.getDescribe();
  map<String, Schema.SObjectField> fieldMap = objDescribe.fields.getMap();
  list<Schema.PicklistEntry> values = fieldMap.get('MailingCountry').getDescribe().getPickListValues();

  List<SelectOption> options = new List<SelectOption>();
  for (Schema.PicklistEntry v : values){
    options.add(new SelectOption(v.getLabel(), v.getLabel()));
  }
  return options;
}	

Visualforce Page code:

<apex:selectList id="countries" value="{!tmpContact.MailingCountry}" size="1" required="true">
  <apex:selectOptions value="{!countries}"/>
</apex:selectList>
Tagged with , , , , 0 komentarzy

Dodaj komentarz

Your email address will not be published. Please enter your name, email and a comment.