2

I have a list of records on GET request which is shown on UI with a checkbox.

@GetMapping("/list")
public String list(Model model) {
    model.addAttribute("records", createRecords());
    return "list";
}

This is my Record POJO:

class Record {
    private boolean selected;   
    private Integer id; 
    private String name;    
    private String phone;
    //....

I am showing in UI as below:

<th:block th:each = "record : ${records}">
<tr>
    <td><input type="checkbox" th:field="*{selected}" th:checked="${record.selected}" /></td>
    <td th:field="*{id}" th:text="${record.id}" />
    <td th:field="${name}" th:text="${record.name}" />
    <td th:field="${phone}" th:text="${record.phone}" />
</tr>
</th:block>

I am having hard time to get the List of selected records on POST from UI. I just gets one object back from POST.

I want something like this in POST mapping:

@PostMapping("/list")
public String select(@ModelAttribute ArrayList<Record> records) {
    //... at least ids of selected records
    //... or all the records back with selected

Please help.

Mahozad
  • 18,032
  • 13
  • 118
  • 133
Anil Bhaskar
  • 3,718
  • 4
  • 33
  • 51
  • This is probably a duplicate of https://stackoverflow.com/questions/36500731/how-to-bind-an-object-list-with-thymeleaf. – ben3000 Sep 16 '17 at 07:35
  • @ben3000 i have the limitation of using the same object, instead of using wrapper object which has list of main objects. – Anil Bhaskar Sep 18 '17 at 15:14

1 Answers1

3

There are a number of potential causes of your problem. The three items listed below should help you get the form mapped correctly:

  1. You should build the form correctly, including using the * notation to reduce repetition, for example:

    <th:block th:each = "record : ${records}">
      <tr>
        <td><input type="checkbox" th:field="*{selected}"/></td>
        <td><input type="text" th:field="*{id}"/></td>
        <td><input type="text" th:field="*{name}"/></td>
        <td><input type="text" th:field="*{phone}"/></td>
      </tr>
    </th:block>
    

    As shown in the Spring + Thymeleaf tutorial

  2. You may need to use the double-underscore notation when looping over ${records} to get each Record filled correctly in your form. As per the Thymeleaf + Spring tutorial:

    ..__${...}__ syntax is a preprocessing expression, which is an inner expression that is evaluated before actually evaluating the whole expression.

    See for example this question.

  3. Double-check that you're handling the resulting list correctly in your Spring @Controller by accepting a List<Record> annotated with @ModelAttribute or @RequestParam. (It looks like you're doing this already.)

    See for example this question.

ben3000
  • 4,629
  • 6
  • 24
  • 43