How to set the value of an object using another object in thymleaf?

Viewed 39

I am passing a post object and current loggedInUser and I want to set the value of "*{author}" to "${loggedInUser.uid}".

    @GetMapping("/showNewBlogForm")
    public String showNewPostForm(Model model) {
        Post post = new Post();
        model.addAttribute("post", post);
        model.addAttribute("loggedInUser", getLoggedInUser());
        return "new_post";
    }

<div class="container">
        <h2>Create Blog</h2>
        <h2 th:text="${loggedInUser.uid}"></h2>
        <form action="#" th:action="@{/publishPost}" th:object="${post}" method="post">
            <input type="text" th:field="*{title}" placeholder="Title" class="form-control mb cp-4" required>
            <input type="text" th:field="*{excerpt}" placeholder="Excerpt" class="form-control mb cp-4" required>
            <textarea type="text" rows="10" th:field="*{content}" placeholder="Content" class="form-control mb cp-4" required></textarea>
            <input type="text" th:value="${loggedInUser.uid}" th:field="*{author}" class="form-control mb cp-4">
            <input type="text" th:field="*{tagsString}" placeholder="Tags" class="form-control mb cp-4">
            <button type="submit" class="btn btn-info col-2"> Publish </button>
        </form>

        <hr>

        <a th:href = "@{/}"> Back to Home Page</a>
    </div>
[1]: https://i.stack.imgur.com/7o7d5.png

1 Answers

Just replace th:field="*{author}" with name="author":

<input type="text" th:value="${loggedInUser.uid}" name="author" class="form-control mb cp-4">

Thanks to th:value the input will contain uid of "loggedInUser" by default.

Thanks to name the input's value will be bound to "author" field of Post object while submitting the form.

Related