Home > front end >  thymeleaf an objects with object properties in one form
thymeleaf an objects with object properties in one form

Time:09-16

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

    @Entity 
    @Table(name = "BOOK")
    public class Books {
    private Long bookId;
     private String bookTitle;
    private Authors author;
  // Getter and Setter
    
   @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="#"  enctype="multipart/form-data" method="post"
               th:action="@{/management/add-book-form}" th:object="${book}">
            <div >
                <div >
                    <input type="text"  th:field="*{book. getBookTitle()}" 
                      placeholder="Author full name">
                    <input type="text"  th:field="*{book. getAuthor()}" 
                      placeholder="Author full name">
                 </div>
             </div>
        </form>

CodePudding user response:

*{...} 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}" />

CodePudding user response:

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

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