Justas S
Justas S

Reputation: 594

Spring boot with Thymeleaf th:object use an object with existing values without overriding them

I'm trying to use my Entity class User as a form object.

@Entity
@Table(name = "users")
public class User implements Serializable {

    @Column(unique = true, nullable = false)
    @Id
    private int id;

    @Column(name = "username")
    private String username;

    @Column(name = "created_at", nullable = false)
    private Timestamp createdAt;

    // Other variables, getters and setters...
}

The view:

<form th:action="@{/users/{id}/save(id=${user.id})}" th:method="POST" th:object="${user}">
<label for="username">Vartotojo vardas</label>
<input type="text" id="username" name="username" th:value="${user.username}" th:field="*{username}"/>
<button type="submit" class="btn btn-success" th:text="Saugoti"></button>
</form>

Now when I show the page containing that form I pass an object named "user" to use in th:value.

What I want to achieve? User contains a field called createdAt after submitting the form it becomes null, even if it was not null before(I printed out in my view before the form to confirm). I want the the form to not change values which I don't tell it to change.

Upvotes: 0

Views: 1920

Answers (1)

yorgo
yorgo

Reputation: 1434

A simple solution would be to add the createdAt field to your form as a hidden field with its value populated.

Maybe a better solution would be to use a data transfer object that contains only fields that you want to update in this particular form. That way you can be sure the fields you want to update will be updated, and the ones you want left alone will be alone.

Upvotes: 1

Related Questions