简体   繁体   中英

Empty form when submitting with SpringMVC and Thymeleaf

I'm trying to edit data (checkboxes) in a table. But when I click on the submit button, the form in the controller is empty

I didn't find a example with thymeleaf so I adapted this example

I use a form object:

public class MyForm {
  private List<MyObj> data;
  // ...
}

The controller with the two methods (GET and POST):

@RequestMapping(value="/edit/", method = RequestMethod.GET)
public String editGet(Model model) {
  MyForm form = new MyForm(data);
  model.addAttribute("myForm", form);
  return "editPage";
}

@RequestMapping(value="/edit/save", method = RequestMethod.POST)
public String editPost(@ModelAttribute("myForm") MyForm myForm, Model model) {
 // here myForm.getData() is empty
}

And my html:

<form th:action="@{/edit/save}" th:object="${myForm}" method="POST">
  <table>
    <thead>....</thead>
      <tbody th:each="myObj : *{data}" th:remove="tag">
        <tr>
          <td><span th:text="${myObj.name}"></span></td>
          <td><input type="checkbox" th:checked="${myObj.isOK}"/></td>
        </tr>
      </tbody>
  </table>
  <input type="submit">Save</input>
</form>

What did I forget?

You should use the following syntax :

<tr th:each="myObj, rowStat : *{data}">

and then set the input fields using :

th:field="*{data[__${rowStat}.index}__].myField}"

That will bind your MyForm with the input data.

More examples can be found here Thymeleaf and forms

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM