2

I have read the previous post: JSF 'total' variable something like c:set in JSTL. Although the answer suggests that the total should come from the backing bean, I have genuine need to do it in the facelet. For my case, I want to display a bank book type datatable, with each row consisting of a date, a description, an amount and a running total. The data come from a JPA get of type List<Entity>. If I did the total in the backing bean I need to iterate the List, create a data model solely for the purpose of a running-total property. This is inefficient indeed.

I tried:

<c:set var="sum" value="0.0" scope="view" />
    <table>
<ui:repeat value="#{xxxBean.items}" var="item">
    <tr>
        <td><h:outputText value="#{item.date1}" /></td>
        <td><h:outputText value="#{item.desc}" /></td>
        <td><h:outputText value="#{item.amount}" /></td>
    <c:set var="sum" value="${sum+item.amount}"/>
        <td><h:outputText value="${sum}" /></td>
    </tr>
</ui:repeat>
    </table>

but it does not work, ${sum} resets to zero for each row. Is there another way, except making a custom component?

Community
  • 1
  • 1
cpliu
  • 21
  • 1
  • 2

1 Answers1

1

This still can be solved using a method in the backing bean:

public class MyBackingBean {

 private Double runningTotal = 0.0;

 public Double getRunningTotal(Item item) {
   Double result = runningTotal;
   runningTotal += item.getAmount();
   return result;
 }

}

Then in your view, use this to display the running total:

<td><h:outputText value="#{xxxBean.getRunningTotal(item)}" /></td>

Not elegant, but it works.

Behrang
  • 46,888
  • 25
  • 118
  • 160
  • No, it does not work. #{xxxBean.getRunningTotal(item)} is unacceptable, only #{xxxBean.runningTotal} - no argument getRunningTotal() – cpliu Aug 15 '11 at 10:54
  • What version of JSF are you using? In JSF 2 you can pass arguments to method expressions. – Behrang Aug 15 '11 at 12:10
  • I use Mojarra 2.0.2 on tomcat 6.0. – cpliu Aug 18 '11 at 11:36
  • Argument support was added in EL 2.2 - so you need Tomcat 7 and Servlet 3.0 support turned on. (This is EL in general - impacting both JSTL *and* JSF) http://stackoverflow.com/questions/5273729/how-to-call-a-method-with-a-parameter-in-jsf – wrschneider Apr 23 '12 at 15:55