Search code examples
jsfprimefacesuirepeat

JSF repeat for row grouping or groupRow


I am not too good with JSF, i have searched but couldn't find similar answer on the net please i need help. I have a set of a sample table below which can grow, it is not certain of how many rows each car has.

...................................................
| ID         | Car        | Year       | Colour   |
|.................................................|
| 37efcc3e   | Audi       | 1994       | Green    |
| 2aacdbd4   | Audi       | 2009       | Yellow   |
| 5dd57389   | BMW        | 1989       | Green    |
| 94f32d8a   | BMW        | 1978       | Orange   |
| d03b3af1   | BMW        | 2001       | Green    |
| 7ca88a0b   | Ford       | 1964       | Silver   |

which i want to display like this below using div to achieve this

Audi
1994   Green     37efcc3e
2009   Yellow    2aacdbd4

BMW    
1989   Green     5dd57389
1978   Orange    94f32d8a
2001   Green     d03b3af1

Ford
1964   Silver    7ca88a0b

How can i use JSF or Primefaces repeat not dataTable to achieve this.
With plain java

List<Product> productList;
for (Product product1 : productList) {
  for (Product product2 : productList) {
    if(product1.getCar().equals(product2.getCar())) {//check if car changes

    }
  }
}
Or can use set
Set<Product> set = new HashSet<Product>(productList);
if(set.size() < list.size()){//check if car changes

}

Primefaces have row grouping or group row with table, I am just wondering how possible how to do it with repeat


Solution

  • Doing this in JSF is not really different than doing it in plain Java

    Pseudocode java

    Assuming a sorted list (like in your table but then sorted) so no additional rewriting of the backing model

    for(int i=0; i<cars.size();i++) {
        if (i==0 || !cars[i].getBrand().equals(car[i-1].getBrand())) {
           System.out.println(cars[i].getBrand());
        }
        System.out.println(cars[i].type + "\t" +cars[i].color + "\t" + cars[i].year);
    }
    

    And in JSF (also 'pseudocode', not tested)

    <table>
      <ui:repeat var="car" value="#{bean.cars}" varStatus="myVarStatus">
    
        <ui:fragment  rendered="#{myVarStatus.index == 0 || !bean.cars.get(myVarStatus.index).brand.equals(bean.cars.get(myVarStatus.index -1).brand}">
            <tr><td colspan="3"><h:outputText value="#{car.brand}"></td></tr>
        </ui:fragment>
    
        <tr>
           <td>#{car.type}</td>
           <td>#{car.color}</td>
           <td>#{car.year}</td>
        </tr>
    
      </ui:repeat>
    </table>