1

I'm trying to create a web page using a thymeleaf template to present a table of Orders with a field that provided a list of products associated with a specific order.

My controller class:

@Controller
public class WebPage {

    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private ProductRepository productRepository;

    @RequestMapping("/test")
    public String index(Model model) {
        model.addAttribute("ordertable", orderRepository.findAll());
        model.addAttribute("producttable", productRepository.findAll());
        return "tablepage";
    }
}

Relevant part of thymeleaf template:

<table class="table">
  <thead>
  <tr>
    <th>ID</th>
    <th>stuff</th>
    <th>Stuuff</th>
    <th>stuff</th>
    <th>products</th>
  </tr>
  </thead>
  <tbody>
  <tr th:each="ordertbl: ${ordertable}">
    <td th:text="${ordertbl.stuffId}"/>
    <td th:text="${ordertbl.stuffname}"/>
    <td th:text="${ordertbl.stuffname}"/>
    <td th:text="${ordertbl.stuff}"/>
    <td>
      <span th:each="producttbl: ${producttable}"><span th:text="${ordertbl.products}"/></span>
    </td>
  </tr>
  </tbody>
</table>

What this does is creates a table of orders but in the final field, it lists all the products contained in the order several times depending how many products are in the product table.

How would I change this so that the the order field lists the products belonging to each row just once. I am aware that this is most likely a nested for loop error, or a problem with my use of findall() method but I'm not sure how to fix it.

I would prefer to use the nested product table rather than fetching the products from the order jpa entity class. Thanks.

Mahozad
  • 18,032
  • 13
  • 118
  • 133
john
  • 31
  • 1
  • 4
  • 1
    Show your product and order entities – Sully Jan 20 '17 at 00:17
  • is that necessary? all thats in them are getters and setters for the variables above like `stuffname` and the creation of lists for the other table. e.g in the order table I have: `private List products; public List getProducts() { return products; }` – john Jan 20 '17 at 00:37

1 Answers1

1

If you're trying to display products of each order, then this line is wrong:

<span th:each="producttbl: ${producttable}"> <span th:text="${ordertbl.products}" /> </span>

You're iterating against the producttable list you have in your model, not of the current ordertbl's products in the loop. It should be

<span th:each="producttbl: ${ordertbl.products}"> <span th:text="${producttbl}" /></span>
isah
  • 5,221
  • 3
  • 26
  • 36