Sunday, 25 August 2013

Autofilling a form using the Play Framework

Autofilling a form using the Play Framework

I have a form that contains some values. When POSTed to the server, the
server validates the information, and if any of the fields are invalid, is
supposed to return the filled form.
The way I currently have it set up is like this.
I have a form that validates 2 fields.
val userForm = Form(
mapping(
"name" -> text,
"age" -> number(min=0, max=100)
)(User.apply)(User.unapply)
)
If the form fails to bind, I load up the same form with the values they
just posted.
def createItem() = IsAuthenticated {
username =>
implicit request => {
createExperienceForm.bindFromRequest().fold(
formWithErrors => BadRequest(
views.html.createItem(formWithErrors)
),
validForm => {
val itemCode = Item.createItem(validForm)
Redirect(routes.Item.item(itemCode).url)
}
)
}
}
The problem is that I have to manually set the value in my HTML page for
each form. eg. @(itemForm: Form[ItemContent])
<input name="age" type="number" class="input-block-level"
value="@itemForm.data.get("age")">
While this works, it will become a bit error prone on larger forms. For
every single field, I need to set the value directly. Is it possible to
autofill these fields?

No comments:

Post a Comment