Dependent picklist using Apex in Salesforce

Sample Code:

Visualforce page:

<apex:page controller="sample">
   
    <apex:form >
   
    <apex:pageBlock>
        <apex:pageBlockSection columns="2">
            <apex:pageblockSectionItem>
                <apex:outputLabel value="State"/>
            </apex:pageblockSectionItem>       
            <apex:pageblockSectionItem>               
                <apex:selectList size="1" value="{!state}">
                    <apex:selectOptions value="{!states}"/>
                    <apex:actionSupport event="onchange" reRender="a"/>
                </apex:selectList>               
            </apex:pageblockSectionItem>
            <apex:pageblockSectionItem>
                <apex:outputLabel value="City"/>
            </apex:pageblockSectionItem>           
            <apex:pageblockSectionItem>
                <apex:selectList size="1" value="{!city}" id="a">
                    <apex:selectOptions value="{!cities}"/>
                </apex:selectList>
            </apex:pageblockSectionItem>           
        </apex:pageBlockSection>       
    </apex:pageBlock>

    </apex:form>

</apex:page>



Apex Code:

public class sample
{
    public String state {get;set;}
    public String city {get;set;}

    public List<SelectOption> getStates()
    {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('None','--- None ---'));       
        options.add(new SelectOption('TN','Tamil Nadu'));
        options.add(new SelectOption('KL','Kerala'));
        return options;
    }
   
    public List<SelectOption> getCities()
    {
        List<SelectOption> options = new List<SelectOption>();
        if(state == 'TN')
        {      
            options.add(new SelectOption('CHE','Chennai'));
            options.add(new SelectOption('CBE','Coimbatore'));
        }
        else if(state == 'KL')
        {      
            options.add(new SelectOption('COA','Coachin'));
            options.add(new SelectOption('MVL','Mavelikara'));
        }
        else
        {
            options.add(new SelectOption('None','--- None ---'));
        }     
        return options;
    }      
}


Cheers!!!

13 comments:

  1. Simple, elegant example to a painfully tricky piece of code.

    Thanks so much, saved a ton of time.

    ReplyDelete
  2. I really appreciate you for taking the time in writing.Can you extend this code to the values coming from soql queries.What i meant is that first picklist values comes from soql and then you populate the second picklist basing on the option chosen in the first pick list from soql query.

    ReplyDelete
  3. Dynamic dependent pick list using apex : i created one Location__c object in that i Created two Pick Lists Country__c and State__c in Country__c pick list i added India,pakistan valus and in state__c pick list i added Andrapradesh,Madhyapradesh,lohore,Quetta if i select a value as India from Country__c pick list in State__c only able to see Andrapradesh,Madhyapradesh if i select a value as pakistan from country_c picklist in state__c only able to see lohore,Quetta by using apex

    ReplyDelete
    Replies
    1. Make use of field dependency..

      Cheers!

      Delete
  4. I have 2 objects named as Manager and another is sales representative which is a master details relationship.. and have the common field named as name , phone no. , states, city ...now i have to make a visualforce page in which i need 1 input field as city and whenever i select city the values on that city can be available on vf page...please help me hw to do this ??

    ReplyDelete
  5. how to write test class for the apex code??

    ReplyDelete
    Replies
    1. Insert the values which you are trying to pass the values in page

      Delete
  6. Is it possible to extend the model to a 3 level dependent pickist? I have tried to do it (say State/City/District in this example) but when I use it the reRendering only works one level. If I change City then District is rerendered with dependent values which is ok. But if I change State only the City level is rerendered automatically but the District remain with the previous option list which is no longer valid (if there is a district XYZ in Coichin city you don't want it to be listed anymore when state is changed to TN). In the VFP I added a section District with id "b" similar to City and I added rerender "b" in the City block (the controller is similar to the example with variable district and a getDistricts() method added).
    Please let me know if want I'm trying is possible and how?
    Thanks
    (below my page section block with < replaced by [ ro escape xml)
    [apex:pageBlock>
    [apex:pageBlockSection columns="2">

    [apex:pageblockSectionItem>
    [apex:outputLabel value="State"/>
    [/apex:pageblockSectionItem>
    [apex:pageblockSectionItem>
    [apex:selectList size="1" value="{!state}">
    [apex:selectOptions value="{!states}"/>
    [apex:actionSupport event="onchange" reRender="a"/>
    [/apex:selectList>
    [/apex:pageblockSectionItem>

    [apex:pageblockSectionItem>
    [apex:outputLabel value="City"/>
    [/apex:pageblockSectionItem>
    [apex:pageblockSectionItem>
    [apex:selectList size="1" value="{!city}" id="a">
    [apex:selectOptions value="{!cities}"/>
    [apex:actionSupport event="onchange" reRender="b"/>
    [/apex:selectList>
    [/apex:pageblockSectionItem>

    [apex:pageblockSectionItem>
    [apex:outputLabel value="District"/>
    [/apex:pageblockSectionItem>
    [apex:pageblockSectionItem>
    [apex:selectList size="1" value="{!district}" id="b">
    [apex:selectOptions value="{!districts}"/>
    [/apex:selectList>
    [/apex:pageblockSectionItem>


    [/apex:pageBlockSection>
    [/apex:pageBlock>

    ReplyDelete
    Replies
    1. Worked my issue around by creating a previousState variable in the controller and using it in the getStates method to check if state value has changed. When it is changed then I force a reset to null of city and district. Not sure is it's the best way to do it, but it works for me, in my case I have a 4 level dependent picklist and that does it.

      Delete
    2. use rerender="a,b"
      by using this it will rerender both the id's

      Delete
  7. unable to execute above code..getting an error

    ReplyDelete
  8. Can you add multiple dependencies to this logic? For example: List options = new List();
    if(state == 'TN' && county == "Cook")

    ReplyDelete