1

Attribute th:field replaces the th:name attribute in the field with radio buttons with its value. The problem is that I have a great many groups with radio buttons, and the field in which they enter information via th:field one. And it turns out that you can select only one of all the radio buttons, and not one in each group.

<form action="#" th:action="@{/user/save_answer}" method="post">

<div th:each="question : ${questions}">
    <span th:text="${question.getValueQuestion()}">question</span>

    <ul>
    <li th:each="variant : ${question.getVariants()}">

            <input th:type="${question.choiceType}" th:id="${variant.id}" th:name="${question.getValueQuestion()}" th:field="${user.variants}" th:value="${variant.id}" >
            <label  th:for="${variant.id}" th:text="${variant.getValueVariant()}">variant </label>
    </li>
    </ul>

</div>
   <button type="submit">Complete</button>
</form>

The bottom line is that I have a questionnaire with questions and in each question there are several possible answers. As you can see, I implemented this with a cycle of answer options within a cycle of questions. Due to the fact that th:name = "question name " is ignored and is taken th:field = "array with user answers", which we have for all answer options, radio buttons are obtained with the same field name = "field with answer options". And thus, as if we can choose only one answer from all the options that are present in all the questions. ${user.variants} - in this field, which belongs to the USER entity, we enter the Variables objects so that later we can see the variants of his answers, the class is described below:

@Data
@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "email")
    private String email;
    @Column(name = "password")
    private String password;
    @Column(name = "first_name")
    private String firstName;
    @Column(name = "last_name")
    private String lastName;
    @Enumerated(value = EnumType.STRING)
    @Column(name = "role")
    private Role role;
    @Enumerated(value = EnumType.STRING)
    @Column(name = "status")
    private Status status;
    @ManyToMany(cascade = { CascadeType.ALL })
    @JoinTable(
            name = "user_variant",
            joinColumns = { @JoinColumn(name = "user_id") },
            inverseJoinColumns = { @JoinColumn(name = "variant_id") }
    )
    private Set<Variants> variants = new HashSet<>();
}
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private QuestionnairesRepository questionnairesRepository;
    @Autowired
    private QuestionsRepository questionsRepository;
    @Autowired
    private VariantsRepository variantsRepository;
    @Autowired
    private UserRepository userRepository;


    @GetMapping
    public String getAllQuestionnaires(Model model){
        model.addAttribute("questionnaires",questionnairesRepository.findAll());
        return "/user_questionnaires";
    }


    @GetMapping("/questionnaire/{id}")
  //  @PreAuthorize("hasAuthority('developers:read')")
    public String listQuestion(@PathVariable Long id, Model model){

            // получаем авторизированного пользователя
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentPrincipalName = authentication.getName();

        Questionnaires questionnaire = questionnairesRepository.findById(id).get();
        model.addAttribute("questionnaire", questionnaire);

        model.addAttribute("user", userRepository.findByEmail(currentPrincipalName).get());

        Iterable<Questions> questionsFromBD = questionsRepository.findAllByQuestionnaire_Id(id);
        model.addAttribute("questions", questionsFromBD);
        return "/user_variants";
    }

    @PostMapping("/save_answer")
    public String saveAnswer(@ModelAttribute("user") User user, Model model){
        System.out.println(user);
        return "/success";
    }
}

There are no errors. here is the html of the page itself, it shows that all the buttons have the same "name"

enter image description here enter image description here

What needs to be fixed so that one radio button is selected for each question and when filling out the answer options are entered in the user options field?

andrewJames
  • 19,570
  • 8
  • 19
  • 51
  • If your `question` object has a unique ID, then you can use that ID to create separate groups of radio buttons. That also allows you to know which response relates to which question when the form data is submitted. You can also take a look at [Multiple radio button groups in one form](https://stackoverflow.com/a/28543929/12567365) for an example of using explicit `` groupings. – andrewJames Dec 04 '21 at 13:17
  • instead of a unique identifier, I use a unique question title question.getValueQuestion() and I used
    as you advised, unfortunately it didn't help
    – Вильсур Муртазин Dec 04 '21 at 16:16
  • Can you show that updated attempt (add it to the question)? What happens? Any errors? – andrewJames Dec 04 '21 at 16:31
  • https://ibb.co/qyPtF94 image https://ibb.co/tZR1T9m . there are no errors. here is the html of the page itself, it shows that all the buttons have the same "name" https://ibb.co/swgVzCS – Вильсур Муртазин Dec 04 '21 at 17:10
  • Sorry - can you add your attempt directly to the question (not as links, and not in comments)? Also, can you clarify (in the question) what the reason for using `${user.variants}` is and what data that provides? These details will help the community to understand your problem more clearly - and will make it more likely that you get a useful answer. – andrewJames Dec 04 '21 at 17:23
  • I don't have a solution, but thank you for the updates. If you are using Spring (I assume you are because of the use of `th:field`), then you can add the relevant Spring tag(s) to your question. – andrewJames Dec 04 '21 at 19:17
  • 1
    Each radio button group needs it's own field, that just how radio buttons work. If you want to have mutiple groups resolve to a single List, you have to do something like this: https://stackoverflow.com/a/68414599/4126893 – Metroids Dec 04 '21 at 21:17
  • @andrewJames the relevant Spring tag(s) - I didn't understand what you mean. Metroids I tried everything, nothing worked out – Вильсур Муртазин Dec 05 '21 at 16:49
  • If you are using Spring (e.g Spring Boot) you can add that as a tag to the question. Currently, the only tag in your question is `thymeleaf`. By adding a Spring tag you are more likely to get Spring experts to look at your question. – andrewJames Dec 05 '21 at 17:02
  • @andrewJames you mean the controller, as I understand it. I added to the question – Вильсур Муртазин Dec 06 '21 at 14:48

0 Answers0