首页 > 解决方案 > th:Thymeleaf 中禁用的对象

问题描述

我有一个基本的 SpringBoot 2.0.5.RELEASE 应用程序。使用 Spring Initializer、JPA、嵌入式 Tomcat、Thymeleaf 模板引擎,并将其打包为可执行的 JAR 文件。

我有一个只读的选择对象,

<select id="selectInvoiceId" th:field="*{invoice}" th:disabled="${resto.id != null}" >
    <option value="0">PLEASE SELECT AN INVOICE</option>
    <option th:each="invoice : ${invoices}" 
            th:value="${invoice.id}" 
            th:text="${invoice.symbol}">
    </option>
</select>

在我的控制器中

@RequestMapping(value = { "/save" }, method = RequestMethod.POST)
public String saveWallet(@Valid @ModelAttribute("wallet") WalletPayload walletPayload, 
    BindingResult bindingResult) {
    ..
}

在 WalletPayload 对象中我有:

@NotNull
private Invoice invoice;

然后我在验证中总是出错,因为发票为空,我想知道只读对象是否有解决方法

我已经尝试过了,但我仍然有错误:

@RequestMapping(value = { "/save" }, method = RequestMethod.POST)
    public String saveWallet(@Valid @ModelAttribute("wallet") WalletPayload walletPayload,
            BindingResult bindingResult) {


        LOG.debug("WalletPayload walletPayload [ " + walletPayload + " ]");

        if (walletPayload.getId() != null) {
            Invoice fakeInvoine = new Invoice("fake-inv");
            fakeInvoice.setId((long)-1);
            walletPayload.setInvoice(fakeInvoice);
        }


        if (bindingResult.hasErrors()) {
            return serverContextPath + WALLET_LIST_VIEW_NAME;
        }

我也尝试使用只读,但它没有作为选择对象上的选项出现

在此处输入图像描述

标签: javaspringspring-mvcspring-bootthymeleaf

解决方案


readonly如果您希望发送值而不希望用户能够编辑它,则应该选择使用。

disabled使用和之间存在细微差别readonly

比较

  • readonly项目不可编辑,但一旦提交就会发送。
  • disabled项目不可编辑,一旦提交就不会发送。
  • readonly项目可以聚焦,而disabled一个则不能。

推荐阅读