Spring Boot+Thymeleaf产品管理系统:自动回显选中流程的time字段
实现流程选择后自动填充时间字段的方案
1. 后端准备流程数据
在跳转新增产品页面的Controller方法中,查询所有流程数据并传递到视图:
@GetMapping("/products/new") public String showAddProductForm(Model model) { model.addAttribute("product", new Product()); // 查询所有流程列表 List<Process> processList = processService.findAll(); model.addAttribute("processList", processList); return "add-product"; }
2. Thymeleaf视图实现自动填充逻辑
在新增产品的HTML页面中,给流程下拉选项绑定data-time属性存储流程时间,通过JavaScript监听下拉框变化事件,自动填充时间到输入框:
<form th:object="${product}" method="post"> <!-- 产品描述输入框 --> <div> <label>产品描述:</label> <input type="text" th:field="*{description}" /> </div> <!-- 流程下拉选择框 --> <div> <label>选择流程:</label> <select th:field="*{process.id}" id="processSelect"> <option value="">请选择流程</option> <option th:each="process : ${processList}" th:value="${process.id}" th:data-time="${process.time}" th:text="${process.type}"></option> </select> </div> <!-- 流程时间输入框(设置为只读,避免手动修改) --> <div> <label>流程时间:</label> <input type="text" id="processTimeInput" readonly /> </div> <button type="submit">提交产品</button> </form> <script> // 获取DOM元素 const processSelect = document.getElementById('processSelect'); const timeInput = document.getElementById('processTimeInput'); // 监听下拉框选择变化 processSelect.addEventListener('change', function() { const selectedOption = this.options[this.selectedIndex]; // 将选中流程的time值填充到输入框 timeInput.value = selectedOption.dataset.time || ''; }); </script>
3. 确认实体类关联关系
确保Product与Process的@ManyToOne关联配置正确:
Product实体类
@Entity public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String description; @ManyToOne @JoinColumn(name = "id_process") private Process process; // 构造方法、getter、setter省略 }
Process实体类
@Entity public class Process { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String type; // 根据实际业务调整类型,比如LocalDateTime、Integer等 private String time; // 构造方法、getter、setter省略 }
内容的提问来源于stack exchange,提问作者PE LI
相关产品推荐
相关产品推荐

