Fetching records by using picklist field dependency in Visualforce Page in Salesforce

By | December 6, 2019

Apex Class

public class mapexample2 {
    public map<string,list<string>> citymap {set;get;}
    public list<selectoption> cityoptions {set;get;}
    public list<selectoption> placeoptions {set;get;}
    public string cityselected {set;get;}
    public mapexample2(){
        citymap = new map<string,list<string>>();
        list<string> hplaces = new list<string>{'lbnagar','srnagar'};
            list<string> cplaces = new list<string>{'Rnagar','Pnagar'};
                citymap.put('HYD', hplaces);
        citymap.put('BNG', cplaces);
        cityoptions = new list<selectoption>();
        placeoptions = new list<selectoption>();
        selectoption n = new selectoption('none','-none-');
        cityoptions.add(n);
        placeoptions.add(n);
        //fetch all the keys from the map and create picklist option for every key
        for(string s:citymap.keySet()){
            selectoption op= new selectoption(s,s);
            cityoptions.add(op); 
        }
    }
    public void getData(){
        placeoptions.clear();
        if(cityselected != 'none'){
            list<string> places = citymap.get(cityselected);
            for(string s:places){
                selectoption sp= new selectoption(s,s);
                placeoptions.add(sp); 
            }
        }else{
            selectoption n = new selectoption('none','-none-');
            placeoptions.add(n);
        }
    }
}

VisualForce Page

<apex:page controller="mapexample2">
    <apex:form >
         <apex:actionFunction name="priorityChangedJavaScript" action="{!getData}" rerender="out"/>
        <apex:outputLabel value="City:"/>
        <apex:selectList size="1" value="{!cityselected}" onchange="priorityChangedJavaScript()">
            <apex:selectOptions value="{!cityoptions}"/>
        </apex:selectList>
        <br/><br/>
        <apex:outputLabel value="Places:"/>
        <apex:selectList size="1" id="out">
            <apex:selectOptions value="{!placeoptions}"/>
        </apex:selectList>
    </apex:form>
</apex:page>

Output

Select the City picklist value then automatically change Places dependency picklist values

Share this...
Share on Facebook
Facebook
Email this to someone
email

Leave a Reply

Your email address will not be published. Required fields are marked *