Menu

How to use groupBy?

2014-04-26
2014-06-12
  • Mark Vejvoda

    Mark Vejvoda - 2014-04-26

    I have the following:

    <jt:forEach items="${shifts}" var="shift" groupBy="id" orderBy="id">Employee: ${shift.employee.fullName} <jt:forEach items="${shift.segments}" var="segment"> ${segment.id} </jt:forEach></jt:forEach>

    Which crashes on the shift.segments on the second loop. If i simply remove the groupBy in the first foreach, it works and no crash. Am I doing something wrong with this syntax? The id property is a Long.

     
  • Randy Gettman

    Randy Gettman - 2014-05-29

    When the groupBy attribute is used on a jt:forEach tag, it groups all items from the collection into groups whose members have the same "group by" properties. This is represented by a class internal to JETT called Group (in the net.sf.jett.model package). A Group is actually the result of the grouping operation. A Group has two properties: obj, one of the objects in the group chosen to "represent" the group, and items to access the full list of objects in that Group.

    It's not obvious, but to access anything common to all objects in shift, you must access the obj first. Instead of Employee: ${shift.employee.fullName}, try Employee: ${shift.obj.employee.fullName}. In the inner foreach, use shift.items to access all shifts with the same id.

    You can also look at the test template that tests the groupBy attribute. In the distribution .zip file, look at /jett/src/jett-core/templates/ForEachTagTemplate.xls or -.xlsx. In the "groupBy" tab, you can see an example of how this is used. I've also attached those 2 template files here.

     
  • Mark Vejvoda

    Mark Vejvoda - 2014-06-12

    You are right, i missed seeing the .obj part, works great and the fix in 0.7.0 allowing sub properties makes this awesome! Thanks again.

     

Log in to post a comment.