views:

1615

answers:

1

I have a Facelets page with a h:dataTable. In each row of the h:dataTable there is a h:selectBooleanCheckbox. If the checkbox is selected a new Object should be created with the data out of the corresponding row.

  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?
+3  A: 

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() {
        for (Item item : items) {
            if (checked.get(item.getId())) {
                // Item is checked. Do your thing here.
            }
        }
    }

    // ...
}

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.

BalusC