Display Column Total in Primefaces data table

Viewed 153

The Primefaces table which will be filtered by different column attributes needs to have a summary row that will update its value as the user change the values in filters. Is there any way to do this?

1 Answers

Create a Column Group footer in the payments.xhtml:

<p:dataTable var="payments" value="#{testBean.payments}" filteredValue="#{testBean.filteredPayments}">

    <p:column headerText="Payment status:" filterBy="#{payment.status}">
        <h:outputText value="#{payment.status}"/>
    </p:column>

    <p:columnGroup type="footer">
        <p:row>
             <p:column colspan="6" headerText="Total: "/>
             <p:column colspan="2" headerText="#{testBean.totalPaymentsSum}"/>
       </p:row>
    </p:columnGroup>

</p:dataTable/>

In the TestBean.java add a method as a getter to calculate the summary row:

List<Payment> payments;
List<Payment> filteredPayments;

public String getTotalPaymentsSum() {
    int total = 0;

    for(Payment payment : filteredPayments) {
        total += payment.getAmount();
    }

    return new DecimalFormat("###,###.###").format(total);
}

For more filter option see the Datatable Filter showcase.

If you have a lot of data and you are using datatable Lazy loading, you can calculate the summary row in the load() or filter() method.

Related