How to update value in <c:set> tag using EL inside a <c:foreach> tag
Asked Answered
P

1

11

I have list which contains some objects in it. The objects have an hours field.

In the <c:foreach> I am iterating the list and fetching the objects.

Now I want to sum up the hours field of all the iterated objects in a totalHours variable.

My code:

<c:forEach var="attendance" items="${list }" varStatus="rowCounter1">
  <tr>
    <td><c:out value="${rowCounter1.count}"></c:out></td>
    <td><c:out value="${attendance.date }"></c:out></td>
    <td><c:out value="${attendance.inTime }"></c:out></td>
    <td><c:out value="${attendance.outTime }"></c:out></td>
    <td><c:out value="${attendance.interval }"></c:out></td>

    <c:set var="totalHours" value="${attendance.Hours += attendance.Hours }"
           target="${attendance}"</c:set>                                       
  </tr>
</c:forEach>

I was trying this, but it gave me the following error:

javax.el.ELException: Failed to parse the expression [${attendance.Hours += attendance.Hours }
Pardue answered 31/7, 2012 at 7:19 Comment(1)
Do you want to set totalHours? To what value?Horselaugh
C
27

In Java, it would look like this:

// before the loop:
int totalHours = 0;
for (Attendance attendance : list) {
    totalHours = totalHours + attendance.getHours();
}

So do the same in JSTL:

<c:set var="totalHours" value="${0}"/>
<c:forEach var="attendance" items="${list }" varStatus="rowCounter1">
    ...
    <c:set var="totalHours" value="${totalHours + attendance.hours}"/>
</c:forEach>
Contessacontest answered 31/7, 2012 at 7:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.