问题描述
我使用< h:dataTable>
列出数据库中的数据。我们在页面上有很多记录,现在我想选择多个记录,每行都有一个复选框。我如何才能实现这一点?
I use <h:dataTable>
to list data from database. 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?
推荐答案
我认为您的实体设计精良,具有独特的技术标识符,例如DB的自动递增序列。
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.
然后,添加一个 Map< Long,Boolean>
属性到绑定到
Then, add a Map<Long, Boolean>
property to the bean which is tied to the table.
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)
然后,添加一个列与一个复选框它按实体ID映射到布尔值作为键。
Then, add a column with a checkbox which maps to the boolean value by entity ID as key.
<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();
}
这篇关于如何选择多个< h:dataTable>行使用< h:selectBooleanCheckbox>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!