function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
krishna casukhela 7krishna casukhela 7 

How to fetch values into dependent picklist

I am having a piece of code which fetches countryname along with its code from custom setting
and populates the country name into the visual force page.

In custom setting, type=LIST , anme is Countries__c and it has a field called CountryCode__c.

if the user selects Australia from vf page and click SAVE button then 'CA' is stored in the backend and so on.
The values in custom settings are not very huge.

Now i need to have another picklsit in vf page , which will display the state name based on the country selected.

I want to store the states names also in custom settings(state names are not many just a few).

Here is what I have achieved so far.
 
public List<SelectOption> CountryCodeList=new List<SelectOption>();

public String selectedCountryCode {get; set;}

 public  List<SelectOption> getCountryCodes() 
   {
        if(countryCodeList.isEmpty())
        {
           countryCodeList=new List<SelectOption>();
           List<Countries__c> allCountries = new List<Countries__c>();

           allCountries = [SELECT  Name,CountryCode__c
                                  FROM    Countries__c];

             
          allCountries.sort();
          
List<Countries__c> cList=new List<Countries__c>([select CountryCode__c 
                                                        from Countries__c 
                                                        where CountryCode__c=:selectedCountryCode]);
          
          if (cList.size() > 0)
          {
          
            for(Countries__c country : allCountries )
            {
              
                countryCodeList.add( new SelectOption( country.CountryCode__c, country.Name ) );
            }
          }
          else
          {
             countryCodeList.add(new SelectOption('--Select--', '--Select--'));

          }
       } 
     
        return countryCodeList;
   }
   
   

<apex:selectOption itemValue=" " itemLabel="--Select--"></apex:selectOption>
<apex:selectOptions value="{!countryCodes}"></apex:selectOptions>
</apex:selectList>

Please let me know how to capture value of first picklsit and based on that get the states for that country.
also how to design the custom setting so as to include the states and how to use changes in vf page.

I request the forum members to help me out urgently.

Thanks
krishna
 
Best Answer chosen by krishna casukhela 7
mohdAnasmohdAnas
Hi krishna,
<apex:page controller="countryController">
<apex:form id="myfrm" >
  <apex:selectList value="{!selectedCountryCode}" size="1">                                                    
      <apex:actionSupport event="onchange" action="{!populateState}" reRender="sel1"></apex:actionSupport>
      <apex:selectOption itemValue=" " itemLabel="--Select--"></apex:selectOption>
      <apex:selectOptions value="{!countryCodes}"></apex:selectOptions>
  </apex:selectList>
                                                
                      
  <apex:selectList id="sel1" value="{!selectedState}" size="1">                                                    
   <apex:selectOption itemValue=" " itemLabel="--Select--"></apex:selectOption>
   <apex:selectOptions value="{!StateCodeList}"></apex:selectOptions>
  </apex:selectList>
  </apex:form>
</apex:page>
 
public class countryController{

    public String selectedState { get; set; }
    public String selectedCountryCode {get; set;}
    public List<SelectOption> CountryCodeList=new List<SelectOption>();
    public List<SelectOption> StateCodeList{get;set;}
    
    public  List<SelectOption> getCountryCodes(){
        if(countryCodeList.isEmpty()){
            countryCodeList=new List<SelectOption>();
            List<Countries__c> allCountries = new List<Countries__c>([SELECT  Name,CountryCode__c FROM    Countries__c]);
            allCountries.sort();
            if (allCountries.size() > 0){
                
                for(Countries__c country : allCountries )
                    countryCodeList.add( new SelectOption( country.CountryCode__c, country.Name ) );
            
            }
            else
                countryCodeList.add(new SelectOption('--Select--', '--Select--'));
        
       } 
     
        return countryCodeList;
    }
    
    
    public void populateState()
    {
        List<States__c> stateList=new List<States__c>([select StateCode__c,Country_Code__c from states__c where Country_Code__c=:selectedCountryCode]);
        StateCodeList  = new List<SelectOption>();
        if(stateList.size() > 0){
            stateList.sort();
            for(States__c state : stateList){
                StateCodeList.add( new SelectOption(state.StateCode__c,state.StateCode__c) );
            }  
        }
    }
}


there is your vf page and controller codes; i have tested myself its working fine now.
Hope it helps!

good day !

All Answers

mohdAnasmohdAnas

Hi Krishna,

You are already 

<apex:actionFunction name="SearchState" action="populateState()" rerender="pageBlock"/>

<apex:selectList id="chooseColor" value="{!selectedCountryCode}"  onchange="SearchState();"size="1">
    <apex:selectOptions value="{!countryCodes}"/>
</apex:selectList>

<apex:selectList id="chooseColor" value="{!SelectedState}"  onchange="SearchState();"size="1">
    <apex:selectOptions value="{!statePicklist}"/>
</apex:selectList>

this will capture the value from your Country picklist in "selectedCountryCode" string variable and then populate the new state picklist of state 
 

public string SelectedState {get;set;}
public List<SelectOption> statePicklist {get;set;}
public void populateState(){
	statePicklist = new List<SelectOption> ();
	for(state_CustomSetting__c  st : [Select state__c from state_CustomSetting__c where countrycode__c = :selectedCountryCode]){
		statePickList.add(new SelectOption (st.state__c,st.state__c));
	}
}
 

Make the custom settings with the country code and state field so that they remain mapped

hope this help 

good day

ManojjenaManojjena
Hi krishna ,

Why you want to maintain picklist in custom setting .I think better you can create two picklist and add controlling and dependency then use in page .

Else you need to do more coding to achieve this .

If you want to add picklist in cutom setting it will be a developer dependent always .
YOu can do one thing you can craete object country and state craete record and have relationship and use in code .

Let me know if it helps !!
Thanks 
Manoj
krishna casukhela 7krishna casukhela 7
Hi mohdAnas
For country=Canada, the states data is   Alberta":"Alberta

I created a new custom setting called States__C and under this two fields , CountryCodes__c and StatesCode__c.
CountryCodes__c=CA
StatesCode__c=Alberta

Here is the code what I have done.
public String selectedCountryCode {get; set;}

    public List<SelectOption> CountryCodeList=new List<SelectOption>();
    
    public List<SelectOption> StateCodeList{get;set;}
public  List<SelectOption> getCountryCodes() 
   {
        if(countryCodeList.isEmpty())
        {
           countryCodeList=new List<SelectOption>();
           List<Countries__c> allCountries = new List<Countries__c>();

          allCountries = [SELECT  Name,CountryCode__c
                                  FROM    Countries__c];

             
          allCountries.sort();
          
          List<Countries__c> cList=new List<Countries__c>([select CountryCode__c 
                                                                  from Countries__c 
                                                                  where CountryCode__c=:selectedCountryCode]);
          
          if (cList.size() > 0)
          {
          
            for(Countries__c country : allCountries )
            {
              
                countryCodeList.add( new SelectOption( country.CountryCode__c, country.Name ) );
            }
          }
          else
          {
             countryCodeList.add(new SelectOption('--Select--', '--Select--'));

          }
       } 
     
        return countryCodeList;
   }
   
   
    public void populateState()
    {
    
    List<States__c> stateList=new List<States__c>();
    
    stateList=[select StateCode__c,CountryCode__c
        from states__c 
        where
        CountryCode__c=:selectedCountryCode];
        
        system.debug('stateList'+stateList);
        
       if (stateList.size() > 0)
          {
          stateList.sort();
            for(States__c state : stateList)
            {
              
                StateCodeList.add( new SelectOption(state.StateCode__c,state.StateCode__c) );
                system.debug(statecodeList);
            }  
           }
    }

VF page
   <apex:actionFunction name="SearchState" action="{!populateState}" rerender="sel1"/>

  <apex:selectList value="{!fanCountry_Region}" size="1"  onchange="searchstate();>                                                    
  <apex:selectOption itemValue=" " itemLabel="--Select--"></apex:selectOption>
  <apex:selectOptions value="{!countryCodes}"></apex:selectOptions>
  </apex:selectList>
                                                
                      
  <apex:selectList id="sel1" value="{!selectedState}" size="1" onchange="searchstate();">                                                    
   <apex:selectOption itemValue=" " itemLabel="--Select--"></apex:selectOption>
   <apex:selectOptions value="{!StateCodeList}"></apex:selectOptions>
  </apex:selectList>
                                                 

But the states are not populated when I select Country as Canada.

Please help me to fix this issue urgent.

Thanks
krishna

 
mohdAnasmohdAnas
Hi krishna,
<apex:page controller="countryController">
<apex:form id="myfrm" >
  <apex:selectList value="{!selectedCountryCode}" size="1">                                                    
      <apex:actionSupport event="onchange" action="{!populateState}" reRender="sel1"></apex:actionSupport>
      <apex:selectOption itemValue=" " itemLabel="--Select--"></apex:selectOption>
      <apex:selectOptions value="{!countryCodes}"></apex:selectOptions>
  </apex:selectList>
                                                
                      
  <apex:selectList id="sel1" value="{!selectedState}" size="1">                                                    
   <apex:selectOption itemValue=" " itemLabel="--Select--"></apex:selectOption>
   <apex:selectOptions value="{!StateCodeList}"></apex:selectOptions>
  </apex:selectList>
  </apex:form>
</apex:page>
 
public class countryController{

    public String selectedState { get; set; }
    public String selectedCountryCode {get; set;}
    public List<SelectOption> CountryCodeList=new List<SelectOption>();
    public List<SelectOption> StateCodeList{get;set;}
    
    public  List<SelectOption> getCountryCodes(){
        if(countryCodeList.isEmpty()){
            countryCodeList=new List<SelectOption>();
            List<Countries__c> allCountries = new List<Countries__c>([SELECT  Name,CountryCode__c FROM    Countries__c]);
            allCountries.sort();
            if (allCountries.size() > 0){
                
                for(Countries__c country : allCountries )
                    countryCodeList.add( new SelectOption( country.CountryCode__c, country.Name ) );
            
            }
            else
                countryCodeList.add(new SelectOption('--Select--', '--Select--'));
        
       } 
     
        return countryCodeList;
    }
    
    
    public void populateState()
    {
        List<States__c> stateList=new List<States__c>([select StateCode__c,Country_Code__c from states__c where Country_Code__c=:selectedCountryCode]);
        StateCodeList  = new List<SelectOption>();
        if(stateList.size() > 0){
            stateList.sort();
            for(States__c state : stateList){
                StateCodeList.add( new SelectOption(state.StateCode__c,state.StateCode__c) );
            }  
        }
    }
}


there is your vf page and controller codes; i have tested myself its working fine now.
Hope it helps!

good day !

This was selected as the best answer
krishna casukhela 7krishna casukhela 7
Hi
I went thru ur code , I have a doubt.

State__c, and  Country_Region__c are two fields in the custom object.

so how do I load values into these two fields when the page loads and also how to save values in object fields.

In country_Region__c the countrycode is stored.

thanks
krishna
mohdAnasmohdAnas

hi krishna,

just add a command button on ur vfpage calling a controller function int it and in this fuction map the string variables that have value of state and country into the fields of custom object , and simply insert it , this will store the record.

or

initialize a custom object into the constructor of your controller and and directly call the value into the fields of this object and with the click of save button insert the record which will store it.

youre welcome,
mohd anas
 

krishna casukhela 7krishna casukhela 7
Hi
I have put up the full code below.
The code is able to populate the countries but its not showing the states for the country.
Also please let me know how to ferch the values and save the values.
<apex:selectList value="{!selectedCountryCode}" size="1">                                                   
       <apex:actionSupport event="onchange" action="{!populateState}" reRender="sel1">
 </apex:actionSupport>
                                           
 <apex:selectOption itemValue=" " itemLabel="--Select--"></apex:selectOption>
<apex:selectOptions value="{!countryCodes}"></apex:selectOptions>

<apex:selectList id="sel1" value="{!selectedState}" size="1">                                                   

   <apex:selectOption itemValue=" " itemLabel="--Select--"></apex:selectOption>

   <apex:selectOptions value="{!StateCodeList}"></apex:selectOptions>

      </apex:selectList>

<apex:command Button action="{!SaveChanges}" value="Save"/>

    public String fanCountry_Region { get; set; }
    public String fanPostalCode { get; set; }
    public String fanState { get; set; }
    public List<SelectOption> CountryCodeList=new List<SelectOption>();
 
    public List<SelectOption> StateCodeList{get;set;}

     public string SelectedState {get;set;}
     
    //Holds the Country Code for the selected option

    public String selectedCountryCode {get; set;}
    public  List<SelectOption> getCountryCodes() 
    {
        if(countryCodeList.isEmpty())
        {
           countryCodeList=new List<SelectOption>();
           countryCodeList.add(new selectOption('','--Select--'));
           List<Countries__c> allCountries = new List<Countries__c>();

          allCountries = [SELECT  Name,CountryCode__c
                                                       FROM    Countries__c];

          allCountries.sort();
          
          List<Countries__c> cList=new List<Countries__c>([select CountryCode__c 
                                                                  from Countries__c 
                                                                  where CountryCode__c =:SelectedCountryCode]);
          
          if (cList.size() > 0)
          {
          
            for(Countries__c country : allCountries )
            {
              
                countryCodeList.add( new SelectOption( country.CountryCode__c, country.Name ) );
            }
          }
          else
          {
             countryCodeList.add(new SelectOption('--Select--', '--Select--'));

          }
       } 
       return countryCodeList;
   }
   
   public void populateState()
   {
   
     List<States__c> stateList=new List<States__c>([select StateCode__c,CountryCode__c
                                                        from States__c
                                                        where CountryCode__c=:fanCountry_Region]);
                                                      
     StateCodeList = new List<SelectOption>();
     
     if (stateList.size() > 0)
     {
        stateList.sort();
        
        for(States__c state : stateList)
        {
         StateCodeList.add(new SelectOption(state.StateCode__c,state.StateCode__c));
        }
     
     }
                                                             
   }
    public void btn_profile_saveChanges()
   {
        if (fan != NULL)
       {
          fan.State__c=SelectedState;  // ??
           fan.Country_Region__c=fanCountry_Region;      
      }     }
 
public PrefCenterCTRL(){
        
        encryptedfanID=ApexPages.currentpage().getparameters().get('id');
        if(String.isBlank(encryptedfanID))
        {
                ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.INFO,'Invalid Id.');
                ApexPages.addMessage(myMsg);
                return;
        }else{
            
            try{
       
         fetchfanvalues();
            }catch(System.QueryException ex){
                
                Apexpages.addMessage(new Apexpages.Message(Apexpages.Severity.ERROR, 'No Record'));
            }   
        }       
    }

public void fetchfanvalues(){
                fan = new fan__c();
         
        fan=[SELECT id,Country_Region__c ,State__c,
              FROM fan__c 
              WHERE Encrypted_ID__c=:encryptedfanID];
                
         if (fan != NULL){             
                selectedCountryCode=fan.Country_Region__c;  // ??
                SelectedState=fan.State__c;              
           
 if(!string.isBlank(fan.Country_Region__c)){              
           fanCountry_Region=fan.Country_Region__c; 
            }
}
Please help me to fix this.

Thanks
krishna