thymeleaf an objects with object properties in one form

Viewed 25

I have two objects a Books and an Authors. The author is a property of the Book.

Book pojo:

@Entity 
@Table(name = "BOOK")
public class Books {
  private Long bookId;
  private String bookTitle;
  private Authors author;
  // Getter and Setter
}

Authors pojo:

@Entity
@Table(name = "AUTUORS")
public class Authors {
  private Long authorId;
  private String authorFullName;
  //getter and setter
}

I need to make a form with two inputs for entering book title and Author name.

Like the following:

       <form action="#" class="form" enctype="multipart/form-data" method="post"
               th:action="@{/management/add-book-form}" th:object="${book}">
            <div class="form-row ">
                <div class="form-group col-md-3">
                    <input type="text" class="form-control" th:field="*{book. getBookTitle()}" 
                      placeholder="Author full name">
                    <input type="text" class="form-control" th:field="*{book. getAuthor()}" 
                      placeholder="Author full name">
                 </div>
             </div>
        </form>
2 Answers

*{...} expressions automatically use the th:object. So the expression *{bookTitle} roughly translates to ${book.bookTitle} and *{author.authorFullName} to ${book.author.authorFullName}

This should work for you:

<input type="text" th:field="*{bookTitle}" />
<input type="text" th:field="*{author.authorFullName}" />

delete placeholder property from input , and access to field direct by field name:

<form action="#" class="form" enctype="multipart/form-data" method="post"
           th:action="@{/management/add-book-form}" th:object="${book}">
        <div class="form-row ">
            <div class="form-group col-md-3">
                <input type="text" class="form-control" th:field="*{bookTitle}" >
                <input type="text" class="form-control" th:field="*{author.authorFullName}">
             </div>
         </div>
</form> 
Related