[英]How to select multiple rows of <h:dataTable> with <h:selectBooleanCheckbox>
I use <h:dataTable>
to list data from database. 我使用<h:dataTable>
列出数据库中的数据。 We have many records in page, now I would like to select multiple records with a checkbox in each row. 页面中有很多记录,现在我想选择每行带有一个复选框的多个记录。 How can I achieve this? 我该如何实现?
I assume that your entity is that well-designed that it has an unique technical identifier, for example the auto increment sequence from the DB. 我假设您的实体经过精心设计,具有唯一的技术标识符,例如数据库中的自动递增序列。
public class Entity {
private Long id;
// ...
}
If not, you'll need to add it. 如果没有,则需要添加它。
Then, add a Map<Long, Boolean>
property to the bean which is tied to the table. 然后,将Map<Long, Boolean>
属性添加到与表绑定的bean。
private Map<Long, Boolean> checked = new HashMap<Long, Boolean>();
(preinitialization can also happen in (post)constructor, take your pick, at least JSF won't do it for you; oh, give it a getter as well, a setter is not necessary) (预初始化也可以在(后)构造函数中发生,请选择,至少JSF不会为您完成;哦,也给它做一个吸气剂,则不需要一个setter)
Then, add a column with a checkbox which maps to the boolean value by entity ID as key. 然后,添加带有复选框的列,该复选框通过实体ID作为键映射到布尔值。
<h:dataTable value="#{bean.entities}" var="entity">
<h:column>
<h:selectBooleanCheckbox value="#{bean.checked[entity.id]}" />
</h:column>
...
</h:dataTable>
<h:commandButton value="Delete" action="#{bean.delete}" />
Now, in the action method associated with the delete button, you can collect and delete the checked items as follows: 现在,在与“删除”按钮关联的操作方法中,您可以按以下方式收集和删除选中的项目:
public void delete() {
List<Entity> entitiesToDelete = new ArrayList<Entity>();
for (Entity entity : entities) {
if (checked.get(entity.getId())) {
entitiesToDelete.add(entity);
}
}
entityService.delete(entitiesToDelete);
checked.clear();
loadEntities();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.