当折叠调用中的验证失败时,如何访问我的表单属性? [英] How to access my forms properties when validation fails in the fold call?

查看:84
本文介绍了当折叠调用中的验证失败时,如何访问我的表单属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动作,我的表单也这样发布:

I have an action where my form posts too like:

def update() = Action { implicit request =>
  userForm.bindFromRequest().fold(
     errorForm => {
        if(errorForm.get.isDefined) {
           val id = errorForm.get.id // runtime error during form post
        }
        BadRequest(views.html.users.update(errorForm))
     },
     form => {
         val id = form.id   // works fine!
         Ok("this works fine" + form.name)
     }
  )

}

执行上述操作时,出现错误:

When I do the above, I get an error:

[NoSuchElementException: None.get]

如果没有验证错误,则表单发布在fold调用的成功"部分运行正常.

If there are no validation errors, the form post works just fine in the 'success' part of the fold call.

我需要在错误部分获取ID值,该怎么办?

I need to get the id value in the error section, how can I do that?

推荐答案

Form未能绑定到模型时,您将只能使用Map[String, String]形式的数据和验证错误(本质上).因此,您可以将值作为String来访问,但是请记住,它们可能也不可用.

When a Form fails to bind to a model, all you will have available is the data in the form of a Map[String, String] and the validation errors (essentially). So you can access the values as Strings, but keep in mind they also might not be available.

例如:

case class Test(id: Int, name: String)

val testForm = Form {
    mapping(
        "id" -> number,
        "name" -> nonEmptyText
    )(Test.apply)(Test.unapply)
}

现在尝试使用缺少的name字段绑定到该Form:

Now try to bind to this Form with a missing name field:

scala> val errorForm = testForm.bind(Map("id" -> "1"))
errorForm: play.api.data.Form[Test] = Form(ObjectMapping2(<function2>,<function1>,(id,FieldMapping(,List())),(name,FieldMapping(,List(Constraint(Some(constraint.required),WrappedArray())))),,List()),Map(id -> 1),List(FormError(name,List(error.required),List())),None)

您可以使用apply访问各个字段.每个Field都有一个value方法,并返回Option[String].

You can access individual fields using apply. And each Field has a value method with returns Option[String].

scala> errorForm("name").value
res4: Option[String] = None

scala> errorForm("id").value
res5: Option[String] = Some(1)

可能的用法:

errorForm("name").value map { name =>
    println("There was an error, but name = " + name)
} getOrElse {
    println("name field is missing")
}

请记住,非绑定数据只是一个String,因此更复杂的数据结构可能更难访问,并且在大多数情况下将不是类型安全的.

Keep in mind that the non-bound data is only a String, so more complicated data structures may be harder to access, and most of the time it will not be type safe.

另一种方法是直接访问原始的Map:

Another way is to access the raw Map directly:

scala> errorForm.data
res6: Map[String,String] = Map(id -> 1)

这篇关于当折叠调用中的验证失败时,如何访问我的表单属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆