我有这张桌子:
<h:form>
<p:dataTable id="books" value="#{ordersBean.userOrders}" var="book" selection="#{ordersBean.selectedBook}">
<p:column>
<f:facet name="header">Order ID</f:facet>
<h:outputText value="#{book[0]}"/>
</p:column>
<p:column>
<f:facet name="header">Title</f:facet>
<h:outputText value="#{book[1]}"/>
</p:column>
<p:column>
<f:facet name="header"></f:facet>
<p:commandButton id="selectRowBtn" value="select" action="#{ordersBean.showSelectedBook}"/>
</p:column>
</p:dataTable>
</h:form>
我希望当我点击每个select
按钮时,它会将行信息分配给selectedBook
属性并以showSelectedBook()
方式显示:
以下是ordersBean
:
private Book selectedBook = new Book();
public Book getSelectedBook() {
return selectedBook;
}
public void setSelectedBook(Book selectedBook) {
this.selectedBook = selectedBook;
}
public void showSelectedBook() {
System.out.println("In selected Book(), book: " + getSelectedBook());
}
但结果是:
In selected Book(), book: null
答案 0 :(得分:1)
应该是这样的:
XML代码:
<p:commandButton id="selectRowBtn" value="select"
action="#{ordersBean.showSelectedBook}">
<f:param name="bookId" value="#{book[0]}" />
</p:commandButton>
Java bean方法:
public void showSelectedBook() {
Map<String,String> params =
FacesContext.getExternalContext().getRequestParameterMap();
int bookId = Integer.valueOf(params.get("bookId"));
for(Book book : bookList){
if(book.bookId == bookId){
selectedBook = book;
break;
}
}
System.out.println("In selected Book(), book: " + getSelectedBook());
}
此外,您必须了解将参数发送到操作的模式,请参阅下面的链接。 http://www.mkyong.com/jsf2/4-ways-to-pass-parameter-from-jsf-page-to-backing-bean/
答案 1 :(得分:1)
如果您想要显示所选的图书,则必须设置selectionMode="single"
,并且不需要在每行中添加commandButton
,只需指定一个commandButton
这样的页脚方面:
<f:facet name="footer">
<p:commandButton id="selectRowBtn" value="select" action="#{ordersBean.showSelectedBook}"/>
</f:facet>
您的主要问题就是您要为new Book()
变量设置selectedBook
,因此null
值为selectedBook
,这个声明:
private Book selectedBook = new Book();
应该是:
private Book selectedBook;
您不必在new Book()
中实例化selectedBook
。
查看此Showcase中的第二个示例,了解其工作原理。
答案 2 :(得分:1)
更好的解决方案,没有选择按钮:
Xml代码:
<p:dataTable id="ListBook"
value="#{ordersBean.bookList}"
selection="#{ordersBean.selectedBook}" var="book"
rowKey="#{book.id}" selectionMode="single">
<p:ajax event="rowSelect"
listener="#{ordersBean.onRowSelectDataTable()}"
update="ListBook" />
..... <columns> ..
</p:datatable>
Java bean:
private Book selectedBook=new Book();
private boolean headerButtonsDisabled=true;
//add a List object for all books (bookList) with getter and setter
public boolean isHeaderButtonsDisabled() {
return headerButtonsDisabled;
}
public void setHeaderButtonsDisabled(boolean headerButtonsDisabled) {
this.headerButtonsDisabled = headerButtonsDisabled;
}
public void onRowSelectDataTable() {
this.setHeaderButtonsDisabled(false);
}
public Book getSelectedBook() {
return selectedBook;
}
public void setSelectedBook(Book selectedBook) {
this.selectedBook = selectedBook;
}