yns89
yns89

Reputation: 37

Primefaces datatable populating when commandButton pressed

I want to load data to datatable when commandButton pressed in primefaces. When page load first, the datatable must be empty but after clicked the commandButton, the datatable must be loaded! How can I do. I'm newbie at the primefaces.

Upvotes: 1

Views: 4973

Answers (2)

SteveS
SteveS

Reputation: 1030

From what you described in your question, here is a sample (This is just a working sample of what @Manuel described). Since the List on the backing bean is empty, at initial render, the datatable will be empty. When you click the commandbutton, it will fire the doPopulateList() method. This method will then populate the list. Finally, the update attribute will cause the datatable to reload the list from the backing bean. This time the List will be populated with 4 records.

<h:body>
    <h:form>
        <p:dataTable id="fooTable" value="#{dataTableBean.dataTableList}" var="record">
            <p:column><h:outputText value="#{record}"/></p:column>
        </p:dataTable>

        <p:commandButton value="Populate DataTable" actionListener="#{dataTableBean.doPopulateList()}" update="fooTable"/>
    </h:form>
</h:body>

DataTableSample backing bean:

@ManagedBean
@ViewScoped
public class DataTableBean implements Serializable {
    List<String> dataTableList = new ArrayList<String>();

    /**
     * @return the dataTableList
     */
    public List<String> getDataTableList() {
        return dataTableList;
    }

    /**
     * @param dataTableList the dataTableList to set
     */
    public void setDataTableList(List<String> dataTableList) {
        this.dataTableList = dataTableList;
    }

    public void doPopulateList(){
        dataTableList.add("Record1");
        dataTableList.add("Record2");
        dataTableList.add("Record3");
        dataTableList.add("Record4");
    }
}

Upvotes: 2

Manuel
Manuel

Reputation: 4228

Don't initialize your dataTable value when the page loads at first. After that you can update p:dataTable

by updating it's id. Just add

<p:dataTable id="dataTableId" ...>

<p:commandButton update="dataTableId" ..>

to your commandButton. In addition you need to use either an

action="#{bean.addStuffToDataTable}"

or

actionListener="#{bean.addStuffToDataTable}"

as an attribute in your p:commandButton in order to populate data in your dataTable. Be sure to read Differences between action and actionListener before you use one of these attributes.

Upvotes: 2

Related Questions