Issue
I have a class, called A with multiple fields, and another class called B that has an object of class A.
In the form the th:object is of class B
Then in the html file I want to get the input using thymeleaf for a field in class A in th:field
So normally I would do th:field="*{field}"
, but the field is not inside class B it is inside class A...so how do i do th:field="{B.Aobj.field}"
please?
I have tried
Solution
You don't need to add A to the model. You can access attributes of child objects just by adding extra dots .
. For example, if your classes look like this:
class Directions {
private int miles;
private Location source;
private Location destination;
// all the getters and setters
}
class Location {
private String name;
private String address;
// all the getters and setters
}
You can access both A
and B
's attributes by dot-walking.
<form th:object="${directions}">
<!-- properties of a -->
<input type="text" th:field="*{miles}" />
<!-- properties of b -->
<input type="text" th:field="*{source.name}" />
<input type="text" th:field="*{source.address}" />
<input type="text" th:field="*{destination.name}" />
<input type="text" th:field="*{destination.address}" />
</form>
Answered By - Metroids
Answer Checked By - David Marino (JavaFixing Volunteer)