Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting th:field in Thymeleaf

I have a form input field in Thymeleaf. The field (bookingEntry.datefrom in the code snippet below) is type Date. I use a datepicker to allow the user to select and format the required date to enter the field. This is all fine.

However, I want the initial value of the date (which I have set to the current date) to be displayed in the format that I choose. So, how do I format the date initially shown in a th:field. th:value is ignored (Thymeleaf is getting the value from the backing object, as it should) and I can't seem to apply a format to the th:field.

Thymeleaf code is:

<input type="text" class="form-control getdate"
       th:field="*{datefrom}" placeholder="Date From"
       th:value="${#dates.format(bookingEntry.datefrom, 'dd-MMM-yyyy')}"/>

I'm sure that I could use a String which is initialise in any format that I choose, rather than a Date type, but I wondered if there was a way to format initial values in a th:field?

Many thanks

like image 535
Theseus Avatar asked Dec 03 '13 21:12

Theseus


People also ask

How do you change the input value in Thymeleaf?

You can also change the value in the controller, just make a Java object from $client.name and call setClientName. public class FormControllModel { ... private String clientName = "default"; public String getClientName () { return clientName; } public void setClientName (String value) { clientName = value; } ... }

What is th field in Thymeleaf?

Thymeleaf provides a special attribute th:field responsible for binding input fields with a property in the bean class. This attribute behaves differently depending on whether it is attached to. Thymeleaf supports all-new input types introduced in HTML5 such as type="color" or type="datetime" .


2 Answers

In case your date is null, it will give you error. We have to check the value before we parse the date.

<input  type="text" name="date" 
        th:value="${user.dateOfBirth}?${#dates.format(user.dateOfBirth, 'dd-MM-yyyy')}:''" 
        placeholder="dd-mm-yyyy"  id="pickyDate"/>
like image 53
Lay Leangsros Avatar answered Sep 17 '22 04:09

Lay Leangsros


I missed the simple answer, simply because of my limited knowledge of Spring. I'm adding it here incase it helps any other novices like me. The @DateTimeFormat annotation on the element in the object being passed to the form does the job. It ensures that the Date object is formatted in the way that you wish (irrespective of whether you are using Thymeleaf or not).

In the example above, within the bookingEntry object

@Temporal(DATE)
@DateTimeFormat (pattern="dd-MMM-YYYY")
private Date datefrom;
like image 33
Theseus Avatar answered Sep 18 '22 04:09

Theseus