I am trying to do same small service and sometimes I am sending requests to my Rest Api. I am getting two problems:
How to fill field in form in html using thymeleaf? I have form like this and would like to fill fields with current values (th:value="${}" - not working for me):
<form th:action="@{/offences/edit}" method="post" th:object="${createOffenceForm}"> <input th:field="*{name}" th:value="${currentOffence.name}"/> <input th:field="*{penaltyPoints}" th:value="${currentOffence.penaltyPoints}"/> <input th:field="*{amountOfFine}" th:value="${currentOffence.amountOfFine}"/> <button type="submit">UPDATE</button> </form>
The problem is with loading css styles to html when I redirect to the site with path variable. For example i created html with two buttons. First one is hardcoded:
<a th:href="@{/offences/test}" style="text-decoration: none"><button type="submit">EDIT</button></a>
after redirect my site looks like this (everything works, it should be like that): `
and here is after second button - redirect with path variable:
<a th:href="@{'/offences/edit/' ${offence.id}}" style="text-decoration: none"><button type="submit">EDIT</button></a>
CodePudding user response:
For the issue with your form data not being filled, this is because th:field
and th:value
are not meant to be used at the same time. So th:field
ends up overwriting you value.
In your case I would suggest either manualy setting name (and id) or replacing th:object with the a filled version of the bean you want to return and only using th:field
As for the second issue it looks like a faulty fragment return on a post call to me but need to atleast have the controller functions and more complete html to say anything about that. And in general it's advisable to have 1 question per problem and not bundle things.
CodePudding user response:
Ok so i found soultion.
- To fill fields in form I only had to add to ModelMap form with fields. Something like this and thymeleaf autofilled fields in html.
modelMap.addAttribute("createOffenceForm", new CreateOffenceForm(offenceDTO.getName(), offenceDTO.getPenaltyPoints(), offenceDTO.getAmountOfFine()));
- Second solution is simple too. When changed mapping in Controller from @GetMapping("/path/{id}") to @GetMapping("/path-{id}") - everything works. There is no other problems with styles...