Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

th:disabled objects in Thymeleaf

I have a basic SpringBoot 2.0.5.RELEASE app. Using Spring Initializer, JPA, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.

I have a select object that is readonly,

<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>

in the controller I have

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

and in the WalletPayload object I have:

@NotNull
private Invoice invoice;

then I got always an error in the validation because invoice is null, I would like to know if there is a workaround for the readonly objects

I've tried this, but I have still the error:

@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;
        }

I also tried to use readonly, but it does not appear as an option on the select object

enter image description here

like image 402
Nunyet de Can Calçada Avatar asked Jan 01 '23 20:01

Nunyet de Can Calçada


2 Answers

You should choose to use readonly if you want the values be sent while you don't want the user to be able to edit it.

There is a subtle difference between the use of disabled and readonly

Comparison

  • readonly items are not editable, but will be sent when once submited.
  • disabled items are not editable and are not sent once submited.
  • readonly items are focus-able while disabled one are not.
like image 71
MohammadReza Alagheband Avatar answered Jan 04 '23 15:01

MohammadReza Alagheband


Use this approach:

When the select element is disabled add a hidden element that sets a fake-invoice to the form so the saveWallet method will get a walletPayload with the non-null fake-invoice.

like image 21
Paco Abato Avatar answered Jan 04 '23 15:01

Paco Abato