I have a simple text input field where i have to set default value from one object and save its final value in other. The following code is not working.
<div th:object="${form}">
<input class="form-control"
type="text"
th:value="${client.name}" //this line is ignored
th:field="*{clientName}"/>
</div>
form is DTO object and client is Entity object from database.
What is the correct way to solve this situation?
By not working I mean - lets say that initial values are client.name="Foo" and form.clientName=null. I need that input field display value is "Foo" and after form submission form.clientName value to become "Foo". But the input field displays nothing and on submission form.clientName value still is null;
If anyone is interested, solved this issue using following structure (found the answer in another question).
th:attr="value = ${client.name}"
This question is related to
html
spring
spring-mvc
thymeleaf
You could approach this method.
Instead of using th:field
use html id
& name
. Set value using th:value
<input class="form-control"
type="text"
th:value="${client.name}" id="clientName" name="clientName" />
Hope this will help you
So what you need to do is replace th:field with th:name and add th:value, th:value will have the value of the variable you're passing across.
<div class="col-auto">
<input type="text" th:value="${client.name}" th:name="clientName"
class="form control">
</div>
If you don't have to come back on the page with keeping form's value, you can do that :
<form method="post" th:action="@{''}" th:object="${form}">
<input class="form-control"
type="text"
th:field="${client.name}"/>
It's some kind of magic :
If you matter keeping you form's input values, like a back on the page with an user input mistake, then you will have to do that :
<form method="post" th:action="@{''}" th:object="${form}">
<input class="form-control"
type="text"
th:name="name"
th:value="${form.name != null} ? ${form.name} : ${client.name}"/>
That means :
Without having to map your client bean to your form bean. And it works because once you submitted the form, the value arn't null but "" (empty)
It has 2 possible solutions:
1) You can set it in the view by javascript... (not recomended)
<input class="form-control"
type="text"
id="tbFormControll"
th:field="*{clientName}"/>
<script type="text/javascript">
document.getElementById("tbFormControll").value = "default";
</script>
2) Or the better solution is to set the value in the model, that you attach to the view in GET operation by a controller. You can also change the value in the controller, just make a Java object from $client.name and call setClientName.
public class FormControllModel {
...
private String clientName = "default";
public String getClientName () {
return clientName;
}
public void setClientName (String value) {
clientName = value;
}
...
}
I hope it helps.
Source: Stackoverflow.com