Search code examples
htmlspring-bootthymeleaf

How can I show in a select values that have the ID that I get from the controller?


I have a select controlled by Thymeleaf

<select th:field="*{customer}">
   <option th:each="customer: ${customers}" th:value="${customer.id}" th:text="${customer.name}"></option>
</select>

This select show me all the customers of the DB.

How can I show just the customer with the ID that I get from here:

@GetMapping("/add")
public String addRoute(Model model) {
    model.addAttribute("route", new RouteCommand());

    /*User userAux = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    model.addAttribute("customer", userAux.getCustomer().getId());*/

    return "admin/routes/add";
}

The code that is commented get the ID of the value that I want to show in the select.


Solution

  • I am not sure below works but you can try as I do not have a workspace to test the solution and also I assume you are using Spring Security Tag and user is logged in

    <sec:authentication property="principal.customer.id" var="cId" scope="page" />
    
    <select th:field="*{customer}">
           <option th:each="customer: ${customers.?[id == __${cId}__]}" th:value="${customer.id}" th:text="${customer.name}"></option>
        </select>