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.
<
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.
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>
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
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)
The correct approach is to use preprocessing
For example
th:field="*{__${myVar}__}"