Search code examples
javahtmlspringspring-bootthymeleaf

How to set default form values for objects in Spring Boot : Thymeleaf


Alright, so im trying to learn Spring Boot and thymeleaf. I have object worker that gets submitted and created, put in a database then the thymelaf page is updated to allow me to edit the worker I just created. For the editing process I need to save the Worker object to the database with the same id so it will update it, my problem is that ID part. I dont want the user to input the id on the webpage but I want it to automatically be set. The problem is, Spring Boot doesnt know which object im editing at the moment, but I have a feeling that thymeleaf knows, I just dont know how to go about it.

               <div th:each="woo : ${workers}">
                    <h1 th:text="${woo.getFirstName() + ' ' + woo.getLastName()}"></h1>
                    <form th:action="@{/updateWorker}" th:object="${worker}" method="post">
                        <div>First name:<input type="text" placeholder="John" name="firstName" th:value="${woo.firstName}"/></div>
                        <div>Last name: <input type="text" placeholder="Smith" name="lastName" th:value="${woo.lastName}"/></div>    
                        <button type="submit">UPDATE</button>
                    </form>
                </div>

And So I have this ^... The worker object has a variable id which I would like it to be automatically set to the id of object "woo" on form submission. Any ideas on how to go about it? Also any helpful critique on how I go about writing my thymeleaf template would be much appreciated, thanks.

edit: And so, just an hour later I figured out a partial solution, <button type="submit" class="btn update" name="id" th:value="${woo.id}">UPDATE</button>, that allows me to set one value on button press. Although what if I want to set a few default values in the future, this temporary solution I just found only allows one value, what if I want to set two or even three. Any ideas?


Solution

  • You can create a hidden input with ID value:

    <input type="hidden" name="id" th:value="${woo.id}"/>