简体   繁体   English

如何为 Spring 中的对象设置默认表单值 Boot: Thymeleaf

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

Alright, so im trying to learn Spring Boot and thymeleaf.好的,所以我正在尝试学习 Spring Boot 和 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.我有 object 工作人员被提交和创建,放入数据库然后更新 thymelaf 页面以允许我编辑刚刚创建的工作人员。 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.对于编辑过程,我需要将 Worker object 保存到具有相同 ID 的数据库中,以便更新它,我的问题是 ID 部分。 I dont want the user to input the id on the webpage but I want it to automatically be set.我不希望用户在网页上输入 id,但我希望它自动设置。 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. 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.所以我有这个^...工人object有一个变量id,我希望它在表单提交时自动设置为object“woo”的id。 Any ideas on how to go about it?关于如何 go 关于它的任何想法? Also any helpful critique on how I go about writing my thymeleaf template would be much appreciated, thanks.也非常感谢任何对我 go 关于编写 thymeleaf 模板的有用批评,谢谢。

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.编辑:所以,仅仅一个小时后,我想出了一个部分解决方案, <button type="submit" class="btn update" name="id" th:value="${woo.id}">UPDATE</button> ,它允许我在按钮按下时设置一个值。 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?有任何想法吗?

You can create a hidden input with ID value:您可以使用 ID 值创建隐藏输入:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM