Reputation: 2354
I have a Springboot & Thymeleaf project that is generating the same "names" on my person inputs.
The controller looks like:
@GetMapping("/newEpisode")
public String episodeForm(Model model) {
model.addAttribute("episode", new Episode());
List<Country> countries = countryRepository.findAll();
Set<String> roles = new HashSet<>();
roles.add("Admin");
model.addAttribute("primaryPerson1",new EpisodePerson());
model.addAttribute("primaryPerson2",new EpisodePerson());
model.addAttribute("roles", roles);
model.addAttribute("countries", countries);
return "episode";
}
Some of my HTML looks like:
<input type="text" class="form-control person surname" style="text-transform: uppercase" data-property="surname" placeholder="SURNAME" th:field="${primaryPerson1.person.surname}"/>
But the generated name in the HTML for this tag is not unique:
<input type="text" class="form-control person surname" style="text-transform: uppercase" data-property="surname" id="surname1" placeholder="SURNAME" name="person.surname" value="">
Why are all the person tags in the html sharing the same name for example I have two :
name="person.surname"
Upvotes: 0
Views: 480
Reputation: 3717
You've misused the th:field
attribute.
Its aim is to bind your input with a property in the form-backing bean. So you should either create separate forms for each object and use it in following manner:
<!-- Irrelevant attributes omitted -->
<form th:object="${primaryPerson1}">
<input th:field="*{person.surname}"/>
</form>
...or create a form-backing bean, which would combine both of your objects, e.g.:
public class EpisodeFormBean {
private List<EpisodePerson> episodePersons;
//getter and setter omitted
}
...then add it to a model in your episodeForm
method...
EpisodeFormBean episodeFormBean = new EpisodeFormBean();
episodeFormBean.setEpisodePersons(Arrays.asList(new EpisodePerson(), new EpisodePerson()));
model.addAttribute("episodeFormBean", episodeFormBean);
...and use it in your template as follow:
<!-- Irrelevant attributes omitted -->
<form th:object="${episodeFormBean}">
<input th:field="*{episodePersons[0].person.surname}"/>
<input th:field="*{episodePersons[1].person.surname}"/>
</form>
In the second solution generated names would be unique. I think it's more suitable for your needs.
You should check out Tutorial: Thymeleaf + Spring as there it is well explained. Especially you should notice a phrase:
Values for
th:field
attributes must be selection expressions (*{...}
), which makes sense given the fact that they will be evaluated on the form-backing bean and not on the context variables (or model attributes in Spring MVC jargon).
Upvotes: 1