How to call bean method when clicking on a checkbox
java, jsf, jsf-2
Solution
Use `<f:ajax>` to send an ajax request.
<h:selectBooleanCheckbox value="#{bean.selectAll}" onclick="highlight(this)" class="checkall">
<f:ajax listener="#{bean.onSelectAll}" render="@form" />
</h:selectBooleanCheckbox>
with
private boolean selectAll;
public void onSelectAll(AjaxBehaviorEvent event) {
// If you're using a boolean property on the row object.
for (Item item : list) {
item.setSelected(selectAll);
}
// Or if you're using a Map<Long, Boolean> on item IDs
for (Entry<Long, Boolean> entry : selected.entrySet()) {
entry.setValue(selectAll);
}
}
public boolean isSelectAll() {
return selectAll;
}
public void setSelectAll(boolean selectAll) {
this.selectAll = selectAll;
}
Ideally the bean should be placed in the view scope by `@ViewScoped` to keep it alive across the ajax requests on the same view.
Don't use `binding` to a bean property unless you have a very good reason. It's intented to bind the whole `UIComponent` to the bean which allows dynamic component manipulation, but more than often there are simpler and less obtrusive ways.
Problem
What is the appropriate way to call `selectAll` Java method when from bean when I click on a checkbox? ``` <f:facet name="header"> <h:selectBooleanCheckbox binding="#{bean.selectAll}" onclick="highlight(this)" class="checkall"/> </f:facet> ``` `binding` is not working. I just want to execute the code in this Java method. EDIT ``` private HashMap<String, Boolean> selected = new HashMap<>(); public void selectAll() throws Exception { String SqlStatement = null; if (ds == null) { throw new SQLException(); } Connection conn = ds.getConnection(); if (conn == null) { throw new SQLException(); } SqlStatement = "SELECT ID FROM ACTIVESESSIONSLOG"; PreparedStatement ps = null; ResultSet resultSet = null; int count = 0; try { conn.setAutoCommit(false); boolean committed = false; try { ps = conn.prepareStatement(SqlStatement); resultSet = ps.executeQuery(); selected.clear(); while (resultSet.next()) { selected.put(resultSet.getString("ID"), true); } /* for (Map.Entry<String, Boolean> entry : selectedIds.entrySet()) { entry.setValue(true); } */ conn.commit(); committed = true; } finally { if (!committed) { conn.rollback(); } } } finally { ps.close(); conn.close(); } } ```