Search code examples
htmlspringspring-bootradio-buttonthymeleaf

How can I bind th:field to value of a radio button in a loop


In my HTML I iterate through a list of players (spieler).

<th:block th:each="spieler : ${runde.spieler}" >

Each player should have an unchecked radiobutton within the same group. When one radio button is checked I want to bind the value to an attribute of the particular player. The attribute is a boolean field (zerrissen).

<input type="radio" th:value="${spieler.zerrissen}" th:field="*{runden[__${rundeStat.index}__].spieler[__${spielerStat.index}__].zerrissen}" />

For checkboxes the binding works fine. But with radio buttons its not working.

<input type="checkbox" th:field="*{runden[__${rundeStat.index}__].spieler[__${spielerStat.index}__].gegangen}"/>

How can I bind a radio button to a boolean attribute of my model within a loop?

Edit:

In simple words, I have three spieler. Each spieler has a boolean attribute: spieler.zerrissen. And each spieler has a radio button on the view. If I hit the radio button of spieler 1 and submit the form, the @ModelAttribute spieler - spieler.zerrissen of spieler 1` should be true. How can I achieve this?

the binding to my model is working because I use the th:field attribute. But using th:field means also that the generated name of each radio button is different and so I can check each radio button and not only one.


Solution

  • Radio button aren't designed to be used this way in thymeleaf. A group of radio buttons should all have the same th:field (and selecting a radio button sets that field to the selected value). You can't have a group of radio buttons that map to different fields.

    I think you have two options here:

    1. Use radio buttons mapped to a new field on your th:object. You would add a getter and setter where the getter would loop through the spielers and return the index of the first spieler where where zerrissen == true and the setter would take the index of the spieler and set zerrissen = true on that object (and false on all others). The value of the radio buttons would be the index of each spieler.

    2. Some kind of javascript solution (use checkboxes and javascript/server side validation to make sure they only select one).