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?
Asked
Active
Viewed 6,238 times
2

BalusC
- 1,082,665
- 372
- 3,610
- 3,555

xuanhung2401
- 311
- 1
- 5
- 15
-
Possible duplicate of [How to use JSF's h:selectBooleanCheckbox with h:dataTable to create one object per row?](http://stackoverflow.com/questions/2524514/how-to-use-jsfs-hselectbooleancheckbox-with-hdatatable-to-create-one-object-p) – BalusC Jan 09 '17 at 19:00
1 Answers
6
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.
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)
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();
}

BalusC
- 1,082,665
- 372
- 3,610
- 3,555
-
I have the exact same code but I am getting a NullPointerException at this line `if (checked.get(entity.getId())) {` – unleashed Aug 19 '14 at 14:25