James Cook
James Cook

Reputation: 389

Spring MVC Thymeleaf Kotlin

I'm trying to pass form to controller but object is empty (looks like gets values from default constructor instead of form). And dunno why @Valid doesn't work.

Code:

Endpoint

    @PostMapping("/add") 
fun addDevice(@Valid @ModelAttribute device: Device, model: ModelMap): ModelAndView {
    deviceRepository.save(device)
    return ModelAndView("redirect:/devices/all", model)
}

Entity:

@Entity
data class Device(
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        val id: Int? = null,
        @NotNull
        val name: String? = "",
        @Min(10)
        @Max(30)
        val price: Int? = null,
        @Size(min = 8)
        val secretPhrase: String? = ""
) : Serializable

Form

<h1>Add Device</h1>
    <!--/*@thymesVar id="device" type="com.example.demo.Device"*/-->
    <form action="#" th:action="@{/devices/add}" th:object="${device}" th:method="post">
        <div class="col-md-12">
            <label>Name Cannot Be Null</label>
            <input type="text" minlength="1" th:field="*{name}"></input>
        </div>
        <div class="col-md-12">
            <label>Secret Phrase Min Length 8</label>
            <input type="password" minlength="8" th:field="*{secretPhrase}"></input>
        </div>
        <div class="col-md-12">
            <label>Price Between 10-30</label>
            <input type="number" min="10" max="30" th:field="*{price}"></input>
        </div>
        <div class="col-md-12">
            <input type="submit" value="Add"></input>
        </div>
    </form>

Upvotes: 4

Views: 2396

Answers (1)

aristotll
aristotll

Reputation: 9177

The problem is you use val instead of var in your data class.

And Spring MVC Thymeleaf calls the no args constructor of your entity class(data classes always have one). And cannot set the fields because they are final.

Just replacing val with var solves the problem.

Upvotes: 6

Related Questions