Raphael
Raphael

Reputation: 143

thymeleaf: th:value is ignored when using th:field

I've got a form where I want to edit some user data. So the already stored data is put as th:value and after sending I validate with spring validation and want to give back the form on wrong input. I want the input field to have the value of the input by the user but it always gives me the stored input instead.

That's how an input field looks like

<input type="text" th:value="${product.name}" th:field="*{name}" th:errorclass="fieldError"/>

If the form is loaded the first time the input fields should have the value of the already stored data.

If it's loaded after submit and with an validation error, the input fields should have the value of the user's input.

Is there a way to to that?

Thanks!

Upvotes: 14

Views: 40924

Answers (4)

Fofola
Fofola

Reputation: 86

You have error in your controller (you set wrong value to *{name}), if the input value is wrong after validation error.

Upvotes: 0

Sriparna Ghosh
Sriparna Ghosh

Reputation: 49

Because Attribute th:field is Combination of both th:name and th:value So, either use this:

<input type="text" th:value="${product.name}" th:name="name" th:errorclass="fieldError"/>

Or this:

<input type="text" th:field="*{name}" "th:errorclass="fieldError"/>

Upvotes: 3

gf jiang
gf jiang

Reputation: 19

Using th:field or value, id and name is ok. if you user th:field, you can write this:

<input type="text" th:field="${product.name}" th:value="${product.name}" "th:errorclass="fieldError"/>

Upvotes: 1

Ostap Gonchar
Ostap Gonchar

Reputation: 782

Attribute th:field will replace attributes value, id and name in your input tag.

Instead, use plain th:id, th:value and th:name without using th:field. Then you will get what you wanted.

Then it will look like:

<input type="text" th:value="${product.name}" th:name="name" th:id="name" th:errorclass="fieldError"/>

Similar answer is here: How to set thymeleaf th:field value from other variable

Upvotes: 30

Related Questions