I hav开发者_JAVA百科e 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?
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 article.
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>
You can use like this. I am not sure it will work or not because I have used <ice:selectOneMenu>
tag and it worked perfectly.
<ice:selectOneListbox
id="paymnent" rows="10" tabindex="4"
value="#{paymentVoucherReportAction.reportType}"
style="width: 200px;height: 20px;">
<f:selectItems id="AutoCmpTasdfasdfasdxtItms11"
value="#{paymentVoucherReportAction.lstKeyValueData}" />
</ice:selectOneListbox>
// Bean(Action) File
private List<SelectItem> lstKeyValueData = new ArrayList<SelectItem>(); // getter + setter
private String reportType; // getter + setter
// put this in your init method
List< SelectItem> list = new ArrayList< SelectItem>();
list.add(new SelectItem("PDF Format","PDF Format"));
list.add(new SelectItem("XLS Format","XLS Format"));
setLstKeyValueData(list);
// print this where you want
System.out.println(reportType);
精彩评论