0
votes

I'm using spring mvc with thymeleaf to save a form with a dropdown value. The problem is when saving, I get the error 400 bad request only when I append the foreign key field in the form as a dropdown with th:field="studentTypeCode".

<select id="typeSelect" class="text_box" th:field="*{studentTypeCode}">
    <div th:each="studentTypeCode : ${studentTypeCodes}" th:remove="tag">
        <option th:value="${studentTypeCode.typeId}" th:text="${studentTypeCode.typeName}" />
    </div>
</select>

Student.java

public class Student{
    private String name;
    //... other fields
    //..
    StudentTypeCode studentTypeCode;

    //getters and setters
}

And in the controller I get the Student object using the th:object with the

@ModelAttribute Student student param. Saving the form throws me 400 bad request since the field studentTypeCode is not correctly sent in the request.

1

1 Answers

0
votes

I just found that since I'm using the @ModelAttribute I just need to send the proper value to the Student object with the student type code id. Declaring th:field="*{studentTypeCode.studentTypeId}" gives me the exact value(int) selected in the dropdown and I can save this value.

The following code,

<select id="typeSelect" class="text_box" th:field="*{studentTypeCode.studentTypeId}">
    <div th:each="studentTypeCode : ${studentTypeCodes}" th:remove="tag">
        <option th:value="${studentTypeCode.typeId}" th:text="${studentTypeCode.typeName}" />
    </div>
</select>

solved my issue. Also add the BindingResult error after your @ModelAttribute field in the @RequestMapping. Read more this article.