如何在<h:dataTable>或<ui:repeat>中使用<h:selectBooleanCheckbox>来选择多个项目?

c0d*_*d3x 20 datatable jsf multipleselection uirepeat selectbooleancheckbox

我有一个Facelets页面<h:dataTable>.在每一行都有一个<h:selectBooleanCheckbox>.如果选中该复选框,则应在bean中设置相应行后面的对象.

  1. 我该怎么做呢?
  2. 如何在支持bean中获取所选行或其数据?
  3. 或者这样做会更好<h:selectManyCheckbox>吗?

Bal*_*usC 52

最好的办法是将h:selectBooleanCheckbox值绑定到表示行标识符类型的Map<RowId, Boolean>属性RowId.让我们举一个例子,你有一个Item标识符属性id为的对象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}" />
Run Code Online (Sandbox Code Playgroud)

与以下内容结合使用:

public class Item {
    private Long id;
    // ...
}
Run Code Online (Sandbox Code Playgroud)

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.
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

您会看到,地图会自动填充id所有表项作为键,并且复选框值会自动设置为与项关联的地图值id.