Thymeleaf 使用 th:each 动态创建表单

Ala*_*ruz 6 java spring thymeleaf

我想知道如何创建th:object用于th:each. 例如,我有以下代码。

超文本标记语言

<th:block th:each="store: ${stores}">
    <form th:object="${store}" th:action="@{/modify-store}">
        <input th:field="*{idStorePk}"/>
        <input th:field="*{name}"/>
        <input th:field="*{phoneNumber}"/>
        <button type="submit">Modify</button>
    </form>
</th:block>
Run Code Online (Sandbox Code Playgroud)

控制器

@RequestMapping(value = "/stores")
public String getIndex(Model model) {
    model.addAttribute("stores", storeService.getAllStores());
    return "store";
}
Run Code Online (Sandbox Code Playgroud)

因此,我想为每个对象添加一个表单,但似乎不可能,并且出现以下错误。

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'store' available as request attribute
Run Code Online (Sandbox Code Playgroud)

所以,我决定在我的控制器中添加一个@ModelAttribute,但无法返回实际的商店。

@ModelAttribute("store")
public Store getStore(Store store) {
    return store;
}
Run Code Online (Sandbox Code Playgroud)

通过这种方法,我的所有表单都有空值。我也尝试添加 a @PathVariable,但看不到使用 绑定它th:object。有解决办法吗?

Ala*_*ruz 6

所以对于遇到类似问题的人来说。我找到了一个可能对您有所帮助的解决方法。首先,你不能使用th:object,它根本不会削减它。相反,请执行以下操作。

<th:block th:each="store: ${stores}">
    <form class="store-form" th:action="@{/modify-store}">
        <input th:name="idStorePk" th:value="${store.idStorePk}"/>
        <input th:name="name" th:value="${store.name}"/>
        <input th:name="phoneNumber" th:value="${store.phoneNumber}"/>
        <button class="submit-button" type="submit">Modify</button>
    </form>
</th:block>
Run Code Online (Sandbox Code Playgroud)

然后添加类似控制器的东西就可以了。

@PostMapping(value = "/modify-store")
@ResponseBody
public boolean deleteEntry(@ModelAttribute Store store) throws Exception {
    // Your code here...
    return true;
}
Run Code Online (Sandbox Code Playgroud)

如果您想异步发送它,那么您将需要添加一些JS代码才能使其工作。它应该类似于下面的代码。

const forms = document.querySelectorAll('.store-form');
forms.forEach(form => {
   form.addEventListener('submit', event => {

   // Stop the normal form submit triggered by the submit button
   event.preventDefault();

   const formInputs = form.getElementsByTagName("input");
   let formData = new FormData();
   for (let input of formInputs) {
       formData.append(input.name, input.value);
   }

   fetch(form.action,
   {
        method: form.method,
        body: formData
   })
   .then(response => response.json())
   .then(data => console.log(data))
   .catch(error => console.log(error.message))
   .finally(() => console.log("Done"));
});
Run Code Online (Sandbox Code Playgroud)