如何在表单解析错误块中访问请求/会话数据?

时间:2017-08-16 20:26:01

标签: scala playframework

我在onError块中返回视图,此视图已传入隐式Flash和ApplicationContext。 ApplicationContext保存来自会话的用户数据,我不知道如何从onError访问它:

  def userFormSubmitted() = Action(parse.form(dataForm, onErrors = (formWithErrors: Form[UserForm]) => {
    // to get rid of error I provide these 2 implicits
    // implicit val applicationContext: ApplicationContext = ApplicationContext(None)
    // implicit val flash: Flash = Flash()
    BadRequest(views.html.user.userFormPage(formWithErrors))
  })) { implicit request =>
    val data = request.body
    // rest of code
  }

ApplicationContext由特征创建:

case class ApplicationContext(user: Option[User])

trait ApplicationController extends Controller {

  implicit def context[A](implicit request: Request[A]): ApplicationContext = {
   //skipped
  }

}

模板将其注入:

@(dataForm: Form[UserForm])(implicit messages: Messages, context: ApplicationContext, flash: Flash)
@main("User Edit Form") { ... }

如果输入错误数据onError,但没有注释implicits代码甚至没有编译错误: 找不到参数上下文的隐含值:traits.ApplicationContext

1 个答案:

答案 0 :(得分:0)

我认为你已达到parse.form身体解析器所能做的上限。

如果您切换到使用bindFromRequest approach to handling form submission,您可以将这些内容纳入范围,一切都会有效:

def userFormSubmittedNew() = Action { implicit request =>

  dataForm.bindFromRequest.fold(
    formWithErrors => {
      BadRequest(views.html.user.userFormPage(formWithErrors))
    },
    goodForm => {
      ...
    }
  )
}