简体   繁体   中英

How to fill a JSF/Primefaces DataTable from a ManagedBean?

I'm realizing my first application using JSF2 and Primefaces 5 . I want that when the user press a button my managed bean creates a new DataTable and fill it with some data. How can I do that from my managed bean? This is a part of code of my managed bean.

...
//This is the managed bean's method executed when the user presses the button.  
public void execute() {
    ...
    //Get the data from database and put the entries in a list of java beans called myList.
    //Here I create a ListDataModel to convert myList in a DataModel to pass to the datatable
    ListDataModel<myJavaBean> tableData = new ListDataModel<myJavaBean>(myList);
    //Then I create a new datatable..
    DataTable dataTable = new DataTable();
    //.. and I set the data
    dataTable.setValue(tableData);
    //I define the columns
    Column idColumn = new Column();
    idColumn.setHeaderText("id");
    Column dateColumn = new Column();
    dateColumn.setHeaderText("date");
    Column timeColumn = new Column();
    timeColumn.setHeaderText("time");
    Column stateColumn = new Column();
    stateColumn.setHeaderText("state");
    //Here I add the columns to the table
    dataTable.getChildren().add(idColumn);
    dataTable.getChildren().add(dateColumn);
    dataTable.getChildren().add(timeColumn);
    dataTable.getChildren().add(stateColumn);
    ...         

When I press the button this part of code create a new DataTable with the correct number of columns and the correct header. Also the number of row is correct but the row are completely empty, I suppose this is due to the fact that I have not bound the Columns with the respective java bean properties of the list. How can I do that?

So you want to create a UI component from a managed bean ???

Maybe I'm missing something here, but a proper and simpler way to acheive this is that the Datatable must be declared in facelet (your_page.hxtml) using <p:datatable> and link it to a backing bean containing the data (ie value="#{yourbean.yourlist}" ).

On startup, your backing bean can be empty. You just have to render UI differently, whether your data is loaded or not (see the "rendered" tag on the datatable component).

Just fill data into the bean when you have to do it (button/execute).

And do not forget to update UI parts (see "update" tag on your action button) in order to refresh altered page regions (datatable at least).

example:

 <p:datatable id="mytable" var="child" value="#{mybean.children}" rendered="#{not empty mybean.children}"> 
 ...
 </p:datatable>
 ...
 <p:button update="mytable">
 ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM