Java – how to get the selected row index in JSF datatable?
I'm at index There is a database on XHTML
<h:dataTable style="border: solid 2px black;"
value="#{IndexBean.bookList}" var="item"
binding="#{IndexBean.datatableBooks}">
<h:column>
<h:commandButton value="Edit" actionListener="#{IndexBean.editBook}">
<f:param name="index" value="#{IndexBean.datatableBooks.rowIndex}"/>
</h:commandButton>
</h:column>
</h:dataTable>
My beans
@ManagedBean(name="IndexBean")
@ViewScoped
public class IndexBean implements Serializable {
private HtmlDataTable datatableBooks;
public HtmlDataTable getDatatableBooks() {
return datatableBooks;
}
public void setDatatableBooks(HtmlDataTable datatableBooks) {
this.datatableBooks = datatableBooks;
}
public void editBook() throws IOException{
int index = Integer.parseInt(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("index").toString());
System.out.println(index);
}
}
My problem is that even if I click different edit buttons, I always get the same index in the server log Suppose a collection is provided to datatable I didn't show it in the beans
If I change the scope from viewscope to requestscope, it will work properly@ What's wrong with viewscoped? Thanks in advance:)
Edit:
<h:column>
<h:commandButton value="Edit" actionListener="#{IndexBean.editBook}" />
</h:column>
public void editBook(ActionEvent ev) throws IOException{
if (ev.getSource() != null && ev.getSource() instanceof HtmlDataTable) {
HtmlDataTable objHtmlDataTable = (HtmlDataTable) ev.getSource();
System.out.println(objHtmlDataTable.getRowIndex());
}
}
Solution
You have bound the < H: datatable > component to the bean All you need to do is:
public void editBook() throws IOException{
int index = datatableBooks.getRowIndex(); // Actually not interesting info.
Book book = (Book) datatableBooks.getRowData(); // This is what you want.
}
< F: param > it's not necessary here See this article for more tips
Update: I can reproduce your problem This may be an @ viewscoped error When the bean is set to @ requestscoped, it works as expected In addition, it works when you delete the component binding and get the component from viewroot itself I have submitted issue 1658 this
