在新增页面,我有一个实体类,里面包含里一个实体类,并且是一对多关系,
private String name;
private string img;
private List list;
如何使用thymeleaf做一个表单form,并且绑定上面的属性,product是一个动态添加的列表,一打开页面是没有数据的,点击按钮新增行。
如下图,点击新增扩展属性,新增一行。
在新增页面,我有一个实体类,里面包含里一个实体类,并且是一对多关系,
private String name;
private string img;
private List list;
如何使用thymeleaf做一个表单form,并且绑定上面的属性,product是一个动态添加的列表,一打开页面是没有数据的,点击按钮新增行。
如下图,点击新增扩展属性,新增一行。
参考GPT和自己的思路:
首先,在Thymeleaf中,我们可以使用th:object指定表单绑定的实体对象。我们需要在表单中使用th:field来绑定实体类的属性。
接下来,我们可以使用th:each来遍历list属性,并使用th:field来绑定list中的每个元素的属性。具体代码如下:
<form th:object="${entity}" method="post">
<label>名称:</label>
<input type="text" th:field="*{name}">
<label>图片:</label>
<input type="text" th:field="*{img}">
<table>
<thead>
<tr>
<th>属性名称</th>
<th>属性值</th>
</tr>
</thead>
<tbody>
<tr th:each="product : ${entity.list}">
<td>
<input type="text" th:field="*{list[__${productStat.index}__].name}">
</td>
<td>
<input type="text" th:field="*{list[__${productStat.index}__].value}">
</td>
</tr>
</tbody>
</table>
<button type="button" onclick="addRow()">新增扩展属性</button>
<button type="submit">提交</button>
</form>
注意,我们在th:field中使用了表达式*{list[__${productStat.index}__].name}
和*{list[__${productStat.index}__].value}
。这里的${productStat}
是用来获取遍历list时的状态变量,其中包含了当前遍历的索引。这样我们就能够正确使用th:field来绑定每个list元素的属性了。