I have a rich datatable with columns that I can filter.
<!-- Data table with filters -->
<h:form>
<rich:dataTable value="#{sessionScope.paymentsBean.payments}" var="payment"
id="table">
<rich:column filterBy="#{sessionScope.payment.invoice}" filterEvent="onkeyup">
<f:facet name="header">Invoice</f:facet>
<h:outputText value="#{sessionScope.payment.invoice}" />
</rich:column>
<rich:column filterBy="#{sessionScope.payment.description}" filterEvent="onkeyup">
<f:facet name="header">Description</f:facet>
<h:outputText value="#{sessionScope.payment.description}" />
</rich:column>
<rich:column filterBy="#{sessionScope.payment.amount}" filterEvent="onkeyup">
<f:facet name="header">Amount</f:facet>
<h:outputText value="#{sessionScope.payment.amount}" />
</rich:column>
</rich:dataTable>
</h:form>
<!-- Total -->
<h:outputText id="total" value="#{sessionScope.paymentsBean.total}" >
<f:convertNumber maxFractionDigits="2" type="currency" currencySymbol="$"/>
</h:outputText>
For the total, I can sum all the amounts in sessionScope.paymentsBean.payments to get the total. Which is $355.00 in the following example.
Invoice Description Amount
1 Cash $5.00
2 Visa $50.00
3 Visa $100.00
4 MasterCard $200.00
Total: $355.00
However, if I filter by "Visa", the table and total would look like:
Invoice Description Amount
2 Visa $50.00
3 Visa $100.00
Total: $355.00
The total should be $150 but getTotal() doesn't know about the filterBy data. Is there a way to dynamically calculate the total based on the filterBy criteria from the rich:datatable?
There's a way to recover the filtered data. You need the table to be binded to a backing bean property and you need it to be a
rich:extendedDataTable
.<rich:extendedDataTable value="#{sessionScope.paymentsBean.payments}" var="payment" id="table" binding="sessionScope.paymentsBean.table">
Binded attribute will be HTMLExtendedDataTable type. After that you will need to create an Ajax call when user types something in the filter, to be called. See
<a4j:support />
component and use it when a key is pressed, as:<a4j:support event="onkeyup" reRender="countBox" action="#{sessionScope.paymentsBean.actionCalculateTotalValue}"/>
Remember calling Ajax method on filterings can be tricky. I sincerely suggest to avoid the table's built-in filters and create your custom ones based in
h:inputText
and implement your ajax calls here. You can take a look into this link.Once the method is called you just need to obtain the filtered rows, calculate the total amount and put in in a variable, over which JSF will update the box when the call is finished. What's the way to get the filtered rows? There you have:
Basically it makes a loop until there are no more available rows in the table. Good luck.