我在Play 2.6中有一个表单提交,其中大多数验证不能预先执行。web应用程序将提交的表单数据发送到另一个项目中的后端,这将为大多数用户错误抛出GrammarException。如何将错误消息和原始表单值传播回视图
这类似于How to access my forms properties when validation fails in the fold call?,但我需要成功时的表单值。
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))
}
)
发布于 2018-05-28 05:17:18
您已经拥有了包含来自请求的所有数据的表单,所以您可以直接使用它。
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))
}
)
发布于 2018-05-26 15:26:27
据我所见,Form的case类有一个错误字段:https://github.com/playframework/playframework/blob/master/framework/src/play/src/main/scala/play/api/data/Form.scala#L37
您也许可以复制收到的表单,添加错误,然后返回它,不是吗?
https://stackoverflow.com/questions/50536807
复制相似问题