Answer the question
In order to leave comments, you need to log in
How to correctly assign a value to an object in thymleaf?
I have an HTML form that has options (select box) for the categoryName field of a Product Object. The value for options is taken from the Category object and should be assigned to the categoryName field of the Product object,
but it doesn't, what could be the problem?
html:
<form action="#" th:action="@{/save}" th:object="${product}" method="post">
<table border="0" cellpadding="10">
<tr>
<td>Наименования:</td>
<td><input required type="text" th:field="*{name}"/></td>
</tr>
<tr>
<td>Описание:</td>
<td><input required type="text" th:field="*{description}"/>
</td>
</tr>
<tr>
<td>Категория:</td>
<td>
<input required type="text" th:field="*{category}"/>
<!-- Проблема! значение из option не происвается в product-->
<select class="form-select form-select-sm" aria-label=".form-select-sm example">
<option selected>Выберите котегорию</option>
<option th:each="category : ${categoryList}" value="${category.id}"
th:text="${product.category}"></option>
</select>
</td>
</tr>
<tr>
<td>Цена:</td>
<td><input required type="number" th:field="*{price}" pattern='[0-9]+(\\.[0-9][0-9]?)?'/></td>
</tr>
<tr>
<td colspan="2">
<button type="submit" class="btn btn-primary">Сохранить</button>
</td>
</tr>
</table>
</form>
// добавить продукт
@RequestMapping("/new_product")
public String showNewProductForm(Model model) {
Product product = new Product();
List<Category> category = categoryService.getAll();
model.addAttribute("categoryList", category);
model.addAttribute("product", product);
return "new_product";
}
Answer the question
In order to leave comments, you need to log in
Good afternoon.
First, make sure the specified string returns something. Add a breakpoint and see if there is a list of categories
List<Category> category = categoryService.getAll();
th:field="*{category}"
category :
For example, cat
and accordingly, change it in the corresponding lines too.<option th:each="category : ${categoryList}" value="${category.id}"
th:text="${product.category}"></option>
th:text="${product.category}"
product.category
, and since product is new: Product product = new Product();
, then there will also be no assigned category for it either.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question