tags:

views:

569

answers:

2

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?

+2  A: 

<h:selectManyListBox value="#{managedBean.list}">

and in the managed bean:

private List list;

(with the appropriate getter and setter, and if possible - using generics)

Bozho
+3  A: 

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.

BalusC
When i assign a list to the values in selectManyListbox, I am getting the following warning. Cannot coerce type java.util.List to java.lang.String, java.lang.Short, java.lang.Character, java.lang.Boolean, java.lang.Double, java.lang.Byte, java.lang.Long, java.lang.Float, java.lang.Integer
Hari
I am using MyEclipse Editter
Hari
Ignore and run it. Eclipse is a epic failure when it comes to JSF/JSP/EL validation.
BalusC