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.

2
  • 1
    Show your product and order entities Commented Jan 20, 2017 at 0: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> products; public List<Products> getProducts() { return products; } Commented Jan 20, 2017 at 0:37

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.