I have a Facelets page with a <h:dataTable>
. In each row there is a <h:selectBooleanCheckbox>
. If the checkbox is selected the object behind the corresponding row should be set in the bean.
- How do I do this?
- How to get the selected rows or their data in a backing bean?
- Or would it be better to do it with
<h:selectManyCheckbox>
?
Your best bet is to bind the
h:selectBooleanCheckbox
value with aMap<RowId, Boolean>
property whereRowId
represents the type of the row identifier. Let's take an example that you've aItem
object whose identifier propertyid
is aLong
:which is to be used in combination with:
and
You see, the map is automatically filled with the
id
of all table items as key and the checkbox value is automatically set as map value associated with the itemid
as key.One way to send in a parameter via
<h:selectBooleanCheckbox>
is to send it in via the title of the Checkbox. In theValueChangeListener
, you can get it from the component using agetAttributes().get("title")
. This helps in cases where you want to send an id value as a parameter (as opposed to the selected row index).In the following example I am using checkboxes to select two or more products to allow the user to compare product specifications on a new web page using JSF 2.0.
It took me a good while to find the following problem (totally obvious now of course) so thought it worth a mention for those trying to use pagination with BalusC's code above (nice answer BalusC, much simpler than I ever imagined it would be).
If you are using pagination you will get nullpointers at the line:
-in BalusC's code above.
This is because only displayed check boxes are added to the Map (doh; slap forehead). For those products whose check boxes are never displayed, due to pagination, this line will result in a null pointer error and a check needs to be added to ignore these null pointers (assuming that all check boxes are unchecked on page load). In order for the user to tick a check box then they need to display the pagination page so all works well there after.
If some or all of the check boxes are required to be ticked on first page load then this will be of no help to you...you will have to manually add those to the Map in order for them to be displayed correctly on page load.
Note: because I am using a JPA 'Entity class from database' object I also needed to use @Transient for the id in my ProductTbl Entity Class as all variables are considered columns in the database by JPA, by default, unless prefixed with @Transient. Also I am using a second link to reset the check boxes, which calls clearSelections(), and my 'submit' is a link calling compareSelectedProducts() rather than a Submit button.
The full code is as follows:
In the 'ProductTbl' Entity class derived from the database :
In the backing bean 'ProductSelection':
In the JSF Web page 'MainSearchResult.xhtml':
In the 'faces-config.xml' file: