Home > Enterprise >  Post form in a th:each section [Spring-Boot Thymeleaf]
Post form in a th:each section [Spring-Boot Thymeleaf]

Time:12-07

I'm displaying a list of objects and for each one of them I want to display a button to access the specific profile page of the selected object. I tried to use the hidden input and pass it the id of the selected object, but in the controller the id is null.

This is the code in the html page.

<table >
                    <thead>
                    <tr>
                        <th scope="col">#</th>
                        <th scope="col">Nome Laboratorio</th>
                        <th scope="col">Indirizzo Laboratorio</th>
                        <th scope="col">Distanza dal Laboratorio</th>
                        <th scope="col">Dettagli</th>
                    </tr>
                    </thead>

                    <tbody>
                    <tr th:each="element,iterationStatus : ${lista}">
                        <td th:text="${iterationStatus.count}" style="width: 10px"></td>
                        <td th:text="${element.laboratorio.nome}"></td>
                        <td th:text="${element.laboratorio.indirizzo}"></td>
                        <td th:text="${#numbers.formatDecimal(element.distanza,1,2,'POINT')}  ' km'"></td>
                        <td>
                            <form th:action="@{/cittadino/selected}" th:object="${laboratorio}" th:method="post">
                                <input  type="hidden"
                                       th:attr="value=${element.laboratorio.id}" th:field="*{id}"/>
                                <button type="submit">Visualizza</button>
                            </form>
                        </td>
                    </tr>
                    </tbody>
                </table>

This is the post-mapping in the controller.

@PostMapping("selected")
    public String laboratorioSelezionato(@ModelAttribute("laboratorio") Laboratorio laboratorio,
                                         Model model) {
        // System.out.println(laboratorio.getId());
        Laboratorio lab1 = laboratorioRepository.getById(laboratorio.getId());
        model.addAttribute("laboratorio",lab1);
        return "laboratorio/indexForUtente";
    }

The field id in the controller is null. What can I try?

CodePudding user response:

It will be easier to use a GetMapping with a path variable.

Change your HTML to this:

...
<td>
 <a th:href="@{/cittadino/{id}(id=${laboratorio.id})}" th:text="#{select.item}"></a>
</td

And in your controller:

@GetMapping("/{id}")
public String laboratorioSelezionato(@PathVariable("id") String id, Model model) {
Laboratorio lab1 = laboratorioRepository.getById(id);
        model.addAttribute("laboratorio",lab1);
        return "laboratorio/indexForUtente";
}

I used String here as type for the id, but if you are using long or UUID, adjust the type as needed.

  • Related