Book Image

Play Framework Essentials

By : Julien Richard-Foy
Book Image

Play Framework Essentials

By: Julien Richard-Foy

Overview of this book

Table of Contents (14 chapters)
Play Framework Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Reading and validating HTML form data


If you try to submit the form, you get an error because the data submitted by your form is not sent to the browser as a JSON blob, as expected by your current Items.create action. Indeed, web browsers send the form data as application/x-www-form-urlencoded content. So, we have to update our action code to handle this content type instead of JSON.

Handling the HTML form submission

The form model you use to produce the HTML form can also be used to process the request body of a form submission. Change the Items.create action as follows:

val create = Action(parse.urlFormEncoded) { implicit request =>
  createItemFormModel.bindFromRequest().fold(
    formWithErrors => BadRequest(views.html.createForm(formWithErrors)),
    createItem => {
      shop.create(createItem.name, createItem.price) match {
        case Some(item) => Redirect(routes.Items.details(item.id))
        case None => InternalServerError
      }
    }
  )
}

The Java equivalent...