How to access/bind the radio buttons values from a form in thymeleaf template

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

How to access/bind the radio buttons values from a form in thymeleaf template

ashok ruhela
Hi,

I have an assessment form where I have some questions having multiple answers(radio buttons). I need to compile the result after the form submission. I have a test class and a question class. The class structure is copied below. I am not able to get the selected values after the form submission. Not sure how to map the fields. Should i create another object or an existing test object can be mapped. Can anyone plz suggest. How can I bind test.question.answer field to get the radio button value. I tried many things but not able to solve it. I highly appreciate if you could help

<form th:action="@{/evaluate/spring/test}" method="post" th:object="${testAnswers}">
        <div th:field="${testName = test.getName()}"></div>
        <div th:each="question,qStat: ${test.getQuestions()}">
            <div>
                <label
                    th:text="${'Question '+ qStat.count + ': ' + question.getDescription()}"
                    th:field="*{questions}"></label>
            </div>
            <div th:each="option,oStat: ${question.getOptions()}">
                <input type="radio" class="input-radio"
                       <b>th:field="*{testAnswers.questions.answer}"
                       th:value="${option.getDescription()}"
                       th:id="${'Q'+qStat.count+'-Opt'+oStat.count}"
                       th:name="${'Question'+qStat.count}">
                <label th:text="${option.getDescription()}"></label>
            </div>
        </div>
        <div>
            <input type="submit" class="btn btn-primary" id="submitspring" value="Submit Test">
        </div>
    </form>

    public class Test {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "name", unique = true)
    private String name;

    @Column(name = "description")
    private String description;

    @Column(name = "duration")
    private int duration;

    @Column(name = "pass_marks")
    private int passingParks;

    @OneToMany( cascade =  CascadeType.ALL)
    @JoinColumn(name = "test_id")
    private Set<Question> questions;
}

public class Question extends BaseModel<Long> {

    @ManyToOne
    public Test test;
    @Column(name = "description")
    private String description;
    @Column(name = "answer")
    private String answer;
    @Column(name = "marks")
    private int marks;
    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "question_id")
    private Set<QuestionOption> options;
}
public class QuestionOption {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column(name = "description")
    private String description;

    @ManyToOne
    private Question question;
}