如何使用< h:selectBooleanCheckbox>在< h:dataTable>中或< ui:repeat>选择多个项目? [英] How to use <h:selectBooleanCheckbox> in <h:dataTable> or <ui:repeat> to select multiple items?
问题描述
我有一个带有<h:dataTable>
的Facelets页面.在每一行中都有一个<h:selectBooleanCheckbox>
.如果选中此复选框,则应在Bean中设置相应行后面的对象.
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.
- 我该怎么做?
- 如何在支持bean中获取选定的行或它们的数据?
- 还是用
<h:selectManyCheckbox>
更好?
- How do I do this?
- How to get the selected rows or their data in a backing bean?
- Or would it be better to do it with
<h:selectManyCheckbox>
?
推荐答案
您最好的选择是将h:selectBooleanCheckbox
值与Map<RowId, Boolean>
属性绑定,其中RowId
代表行标识符的类型.让我们举一个例子,您有一个Item
对象,其标识符属性id
是Long
:
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}" />
与以下项结合使用:
public class Item {
private Long id;
// ...
}
和
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.
}
// ...
}
您会看到,地图自动以所有表项的id
作为键填充,并且复选框值自动设置为与项目id
作为键相关联的地图值.
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.
这篇关于如何使用< h:selectBooleanCheckbox>在< h:dataTable>中或< ui:repeat>选择多个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!