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
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 whiledisabled
one are not.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With