Saturday, August 29, 2009

richfaces DataTable - getting selected row

Unfortunately, a simple thing like getting which row in the rich:DataTable was selected is not so simple!

For excellent examples, see this page:
http://balusc.blogspot.com/2006/06/using-datatables.html

And, in addition, remember this:

1. Binding the datatable in your xhtml to a backing bean datatable (using the 'binding' attribute) will work only if the backing bean is in request scope. If it is in session scope, you will get a duplicate Id error when you refresh or revisit the page.

2. If you put a commandButton (or commandLink) on each row - it will work only if the action handler backing bean is in session scope. If it is in request scope, the action handler will not be called.

So, these two things are in contradiction to each other. The solution, if you are in this situation, is to have two backing beans - one for binding the datatable and another for handling the commandButton!

Now, if the reason you are binding the datatable in the first place is to use dataTable.getRowData() to identify the row - so that you can get to the row object, then you are in trouble. Because the action handler will go to a different backing bean!

The solution is to use f:setPropertyActionListener to pass the selected row object to the commandButton, as below:
<a4j:commandLink value="#{project.name}" action="#{projectBean.view}">
<f:setPropertyActionListener target="#{projectBean.project}" value="#{project}" />
</a4j:commandLink>

The backing bean, in this case projectBean should have a property called 'project' with getters and setters.

1 comment:

  1. I would like to know how to access the selected pickList on the right side in the backing bean. I have a getter and setter defined for the selected picklist. When I read the list and display its size I am not getting it. Please post some code, the xHTML side and the backing bean side for the pickList.

    I have a converter defined for my object. Which converts from my object(List of Faculty) to List of SelectItem in order to display on the left side of the pickList.

    Now I am assuming I should grab the right side list and convert it back to List of Faculty, but I am not able to access that list. I tried using the get method and printing its size, but it prints 0.

    ReplyDelete