'How can I set a default value if a user doesn't send an input in Thymeleaf
Right now - I have a input field on my html that Thymeleaf sticks a '0' in when the page loads. If for some reason that '0' is erased and the form is submitted - I get a NumberFormatException.
Is there a way I can automatically make it '0' if the form is submitted without anything in the input form?
Here's my html form (my th:object is ${npf})
<div class="col-md-2 form-outline">
<input class="form-control" type="text" id="addConcealed" th:field="${npf.numConcealed}" placeholder="C" />
<label class="form-label text-muted" for="addConcealed">Concealed</label>
</div>
Here's the error I get:
[Failed to convert property value of type 'java.lang.String' to required type 'long' for property 'numConcealed'; nested exception is java.lang.NumberFormatException: For input string: ""]
Anyway I can have it default to 0 if there's nothing in the input field rather than erroring out and making the user enter a number?
Solution 1:[1]
There are a couple ways to handle this:
Turn your variable
numConcealedinto anLonginstead of along. Deal with a null value when they erase the field.Use JavaScript, capture the submit just change the field value back to 0 if they submit a blank text field.
Create your own
StringtointConverter and register it for that field. Should work the same way as the normal converter (whatever that is) except it would return 0 for nulls.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Metroids |
