Reputation: 55
Inside a web form I have input boxes like these:
<input type="datetime-local" id="dt" name="dt" value=@form("dt")><br />
<input type="text" id="f0" name="f0" size="12" list=lst>
I am mapping the fields to a class:
case class Data(dt: Date, f0: String...)
When I submit the form I am able to fetch the values inserted in the boxes. However, I wanted to initialize the first input box with the current date. I tried, like it was documented, by returning the following from the main action:
Ok(views.html.index(form.fill(new Data(new Date(), ""))))
But it did not work out.
How can I achieve that?
Thanks!
Upvotes: 1
Views: 411
Reputation: 3251
First define a custom Formatter
that has the date pattern needed by the datetime-local input type using Java's date format pattern:
import play.api.data.format._
val dateTimeLocal: Formatter[Date] = Formats.dateFormat("yyyy-MM-dd'T'HH:mm")
Then define to/from a Form
using mapping
and of
.
val dataForm = Form(
mapping(
"dt" -> of(dateTimeLocal),
"f0" -> text
)(Data.apply)(Data.unapply)
)
Now you can use a form helper to display an <input type="datetime-local">
:
@helper.inputText(dataForm("dt"), 'type -> "datetime-local")
This produces the following HTML snippet, with the correct input type
and date pattern:
<input type="datetime-local" id="dt" name="dt" value="2017-11-16T08:19" />
You'll get a date/time picker when you view this in Chrome, but not currently in browsers like Firefox (as of November 2017). You may wish to consider this note on MDN:
Because of the limited browser support for
datetime-local
, and the variations in how the inputs work, it may currently still be best to use a framework or library to present these, or to use a custom input of your own. Another option is to use separatedate
andtime
inputs, each of which is more widely supported thandatetime-local
.
Upvotes: 3