Search code examples
jsflistboxlabel

How do I set label in h:selectOneListbox?


I have to display a list box with label as value "name" & I am using h:selectOneListbox.

My Code is :

<h:selectOneListbox id="select" value"#{trial.trials}" size="1" title="Select Item...">
<f:selectItems value="#{trial.trials}/>
</h:selectOneListbox>

My trial bean is :

public class trial{

List<trialDataBean> trials = new ArrayList<trialDataBean>();


public trial(){
trialDatBean tdb = new trialDataBean(1,"aatmiya");
trials.add(tdb);
}

public List<trialDataBean> getTrials(){
return trials;
}

public void setTrials() {
this.trials = trials;
}

}

trialDataBean has a property "name" & I want to set it as a label of the ListBox. How do I do this?


Solution

  • In JSF 1.x, you need to create a List<SelectItem> based on your List<Trial>. The constructor of SelectItem can take the option value as 1st argument and the option label as 2nd argument.

    public class Bean {
    
        private Trial selectedTrial;
        private List<Trial> trials;
        private List<SelectItem> selectTrials;
    
        public Bean() {
            trials = loadItSomehow();
            selectTrials = new ArrayList<SelectItem>();
            for (Trial trial : trials) {
                selectTrials.add(new SelectItem(trial, trial.getName()));
            }
        }
    
        // ...
    }
    

    Then you can use it in the view as follows:

    <h:selectOneListbox value="#{bean.selectedTrial}" converter="trialConverter">
        <f:selectItems value="#{bean.selectTrials}" />
    </h:selectOneListbox>
    

    You only need to supply a custom Converter which converts between Trial and String. More detail can be found in this answer.


    In JSF 2.x, you can omit the List<SelectItem> and use the new var attribute in f:selectItems instead:

    <h:selectOneListbox value="#{bean.selectedTrial}" converter="trialConverter">
        <f:selectItems value="#{bean.trials}" var="trial"
            itemValue="#{trial}" itemLabel="#{trial.name}" />
    </h:selectOneListbox>