本文介绍了如何选择多行&lt;h:dataTable&gt;使用 <h:selectBooleanCheckbox>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我使用 列出数据库中的数据.页面中有很多记录,现在我想选择多条记录,每行都有一个复选框.我怎样才能做到这一点?

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?

推荐答案

我假设您的实体设计得很好,它具有唯一的技术标识符,例如来自数据库的自动增量序列.

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.

然后,向绑定到表的 bean 添加 Map 属性.

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>();

(预初始化也可以发生在(后)构造函数中,随你选择,至少 JSF 不会为你做;哦,给它一个 getter,一个 setter 不是必需的)

然后,添加一个带有复选框的列,该复选框以实体 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();
}

这篇关于如何选择多行&lt;h:dataTable&gt;使用 <h:selectBooleanCheckbox>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 03:41
查看更多