How to use <h:selectBooleanCheckbox> in <h:dataTable> or <ui:repeat> to select multiple items?

c0d3x picture c0d3x · Mar 26, 2010 · Viewed 64.4k times · Source

I have a Facelets page with a <h:dataTable>. In each row there is a <h:selectBooleanCheckbox>. If the checkbox is selected the object behind the corresponding row should be set in the bean.

  1. How do I do this?
  2. How to get the selected rows or their data in a backing bean?
  3. Or would it be better to do it with <h:selectManyCheckbox>?

Answer

BalusC picture BalusC · Mar 26, 2010

Your best bet is to bind the h:selectBooleanCheckbox value with a Map<RowId, Boolean> property where RowId represents the type of the row identifier. Let's take an example that you've a Item object whose identifier property id is a Long:

<h:dataTable value="#{bean.items}" var="item">
    <h:column>
        <h:selectBooleanCheckbox value="#{bean.checked[item.id]}" />
    </h:column>
    ...
</h:dataTable>
<h:commandButton value="submit" action="#{bean.submit}" />

which is to be used in combination with:

public class Item {
    private Long id;
    // ...
}

and

public class Bean {
    private Map<Long, Boolean> checked = new HashMap<Long, Boolean>();
    private List<Item> items;

    public void submit() {
        List<Item> checkedItems = checked.entrySet().stream()
            .filter(Entry::getKey)
            .map(Entry::getValue)
            .collect(Collectors.toList());

        checked.clear(); // If necessary.

        // Now do your thing with checkedItems.
    }

    // ...
}

You see, the map is automatically filled with the id of all table items as key and the checkbox value is automatically set as map value associated with the item id as key.