I am having a selectmanyListbox component in my JSF, now i want to store the selected data's into a List. How to do this?
As with every UIInput component, you just have to bind the value attribute with a property of the backing bean. Thus, so:
<h:form>
<h:selectManyListbox value="#{bean.selectedItems}">
<f:selectItems value="#{bean.selectItems}" />
</h:selectManyListbox>
<h:commandButton value="submit" action="#{bean.submit}" />
</h:form>
with the following in Bean class:
private List<String> selectedItems; // + getter + setter
private List<SelectItem> selectItems; // + getter only
public Bean() {
// Fill select items during Bean initialization/construction.
selectItems = new ArrayList<SelectItem>();
selectItems.add(new SelectItem("value1", "label1"));
selectItems.add(new SelectItem("value2", "label2"));
selectItems.add(new SelectItem("value3", "label3"));
}
public void submit() {
// JSF has already put selected items in `selectedItems`.
for (String selectedItem : selectedItems) {
System.out.println("Selected item: " + selectedItem); // Prints value1, value2 and/or value3, depending on selection.
}
}
If you want to use non-standard objects as SelectItem value (i.e. not a String, Number or Boolean for which EL has already builtin coercions), then you'll have to create a Converter for this. More details can be found in this blog article.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With