如何向Play 2.0表单添加全局表单错误以指示乐观锁定失败

Bri*_*ian 5 playframework playframework-2.0

我有一个简单的模型对象:

case class Region(id: String, revision: Option[String], name: String)

object Region {        
    // Returns Some(region) if successful, None if revision doesn't match the latest
    // in the data store
    def insertOrUpdate(region: Region): Promise[Option[Region]]
}
Run Code Online (Sandbox Code Playgroud)

在我的控制器中,我想做这样的事情,但我不知道如何在响应中指出锁定失败.我想添加一个全局表单错误,但无法从API中看到.

def update(id: String) = Action {
    implicit request => regionForm.bindFromRequest.fold(
        formWithErrors => BadRequest(views.html.regions.edit(formWithErrors)),        
        region => Async{
            Region.insertOrUpdate(region).map{
                _ match {
                    case None => {
                    // How do I add a global form error indicating there were server side changes detected
                        BadRequest(views.html.regions.edit(regionForm.fill(region))
                    }
                    case Some(r) => Redirect(views.html.regions.index).flashing(("success", "Update successful")
            }
        }
    )
}
Run Code Online (Sandbox Code Playgroud)

Jul*_*ont 11

适用于Play 2.0.4

实际上,全局错误是没有键的错误(参见globalErrors方法).

没有助手可以添加错误,但你可以自己做,有类似的东西:

regionForm.fill(region)
  .copy(errors = FormError("", "Your Error Message") +: errors)
Run Code Online (Sandbox Code Playgroud)

对于Play 2.1

您可以使用以下withGlobalError方法:

regionForm.fill(region)
  .withGlobalError("Your error message")))
Run Code Online (Sandbox Code Playgroud)