Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store the data's selected in a selectManyListbox into a List in JSF?

Tags:

java

jsf

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?

like image 291
Hariharbalaji Avatar asked Feb 02 '26 14:02

Hariharbalaji


1 Answers

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.

like image 87
BalusC Avatar answered Feb 04 '26 04:02

BalusC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!