scalaconcurrencyplayframework

Play Framework: access form when validation succeeds


I have a form submission in Play 2.6 in which most validation can't be performed up front. The web application sends the submitted form data to a backend in another project, which will throw a GrammarException for most user errors. How can I propagate an error message and the original Form values back to the view

This is similar to How to access my forms properties when validation fails in the fold call?, but I need the form values on success.

form.bindFromRequest().fold(
  formWithErrors => {
    BadRequest(myView(newForm = formWithErrors)(request))
  },
  data => try {
    val results = MyBackend.build(data) // time-consuming
    Ok(views.html.myView(results)
  } catch { // catches most user errors
    case e: GrammarException =>
      val submittedForm = ....? //
      val formWithErrors = submittedForm.withGlobalError(e.getMessage)
      BadRequest(myView(newForm = formWithErrors)(request))
  }
)

Solution

  • You are already have the form with all the data from the request, so you can just use it.

    val formWithBoundData = form.bindFromRequest()
    formWithBoundData.fold(
      formWithErrors => {
        BadRequest(myView(newForm = formWithErrors)(request))
      },
      data => try {
        val results = MyBackend.build(data) // time-consuming
        Ok(views.html.myView(results)
      } catch { // catches most user errors
        case e: GrammarException =>
          val formWithErrors = formWithBoundData.withGlobalError(e.getMessage)
          BadRequest(myView(newForm = formWithErrors)(request))
      }
    )