filemonczyk
filemonczyk

Reputation: 1703

nested objects in thymeleaf

I'm trying to build a form using thymeleaf, my entity includes Collection (List) of objects. I'm struggling to build a proper form for this case.

This is my entity:

@Entity
public class Owner {

    @Id
    @GeneratedValue
    private int id;
    @Column(name = "first_name")
    private String firstName;
    @Column(name = "last_name")
    private String lastName;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "owner")
    private List<Phone> phones;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "owner")
    private List<Pet> pets;

//getterss and setters

this is the Pet.class

@Entity
public class Pet {

    @Id
    @GeneratedValue
    private int id;
    @Column(name = "pet_name")
    private String petName;

    @ManyToOne
    @JoinColumn(name = "owner_Id")
    private Owner owner; 

//getters and setters

and this is my html file for building the form:

<!DOCTYPE html>
<html xmlns:th="http:/www.thymealeaf.org">
<head>
<meta charset="ISO-8859-1"></meta>
<title>Add new owner to database</title>
</head>
<body>
    <div id="form">
        <form th:action="@{/addOwner.do}" th:object="${Owner}" method="post">

            <label for="firstName">First Name: </label> 
            <input type="text" th:field="*{firstName}" /> 

            <label for="lastName">Last Name:</label>
            <input type="text" th:field="*{lastName}" /> 

            <!-- Here is the core problem -->
            <label for="pets">Pet Name: </label>
            <input type="text" th:each="pet : *{pets}"/> 

            <input type="submit" value="add" />
        </form>
    </div>
</body>

so I'm struggling with this:

 <!-- Here is the core problem -->
                <label for="pets">Pet Name: </label>
                <input type="text" th:each="pet : *{pets}"/> 

my problem is, I dont know how to access Pet object in List collection inside of the form so that i could make an input of petName property.

//edit or maybe there is a different way to do this? the obvious way is getting a string from form and then in controller building the string to pet name before adding the object to database?

Upvotes: 3

Views: 2768

Answers (1)

Periklis Douvitsas
Periklis Douvitsas

Reputation: 2491

can you try this and let me know if this worked for you

<div th:each="pet, stat : *{pets}"> 
   <input type="text" th:field="*{pet[__${stat.index}__].petName}" /> 
</div>

Upvotes: 2

Related Questions