Search code examples
javaspringhibernatejpathymeleaf

thymeleaf value to html select input


Controller

@GetMapping("/kosik")
public String kosik(Principal principal,Model model){
    User user = userServices.findByEmail(principal.getName());
    Cart cart = cartServices.findCartByUser(user);
    model.addAttribute("produkty",cartItemServices.findAllCartItems(cart));
    model.addAttribute("cart",cartServices.findCartByUser(user));
    model.addAttribute("user",user);
    return "cart";
}

Html

<ul class="list-group mb-3">
                <li th:each="produkt: ${produkty}" class="list-group-item d-flex justify-content-between lh-condensed">
                    <div>
                        <h6 th:text="${produkt.product.name}" class="my-0"></h6>
                    </div>
                    <span th:text="${produkt.price}" class="d-inline-block"></span><span class="d-inline-block"> €</span>

                    <form th:action="@{/updateCartItem(name=${produkt.product.name})}" th:object="${cartItem}" method="post">
                        <select th:field="*{quantity}">
                            <option th:value="1">1</option>
                            <option th:value="2">2</option>
                            <option th:value="3">3</option>
                            <option th:value="4">4</option>
                            <option th:value="5">5</option>
                        </select>
                        <input type="submit" value="Update" class="btn-sm btn-primary" />
                    </form>
               </li>
            <li th:each="kosik: ${cart}" class="list-group-item d-flex justify-content-between">
                <span>Total Price</span>
                <strong th:text="${kosik.totalPrice}"></strong>
            </li>
        </ul>

Everything is updating, working fine, but i cant get current cartItem quantity to select th:field, it is still 1, i have also tried th:selected, but didnt work..


Solution

  • To fix it, you need to remove th:field and replace it with name and id attributes.

    <select id="quantity" name="quantity">
        <option value="1">1</option>
        ...
        <option value="5">5</option>
        <option value="6" selected="selected">6</option>
         ...
        <option value="10">10</option>
    </select>