如何处理Play中的长格式和不同格式!斯卡拉形式?

cro*_*ies 8 forms scala playframework-2.0

在我的模型中,所有关联的帐户都不是Long正常的整数.但是,在新Play中处理Scala表单时!2.0我只能验证Int表单中的数字而不是表单中的数字Long.

http://www.playframework.org/documentation/2.0/ScalaForms

采取以下形式:

val clientForm: Form[Client] = Form(
    mapping(
      "id" -> number,
      "name" -> text(minLength = 4),
      "email" -> optional(text),
      "phone" -> optional(text),
      "address" -> text(minLength = 4),
      "city" -> text(minLength = 2),
      "province" -> text(minLength = 2),
      "account_id" -> number
    )
    (Client.apply)(Client.unapply)
  )
Run Code Online (Sandbox Code Playgroud)

你看到account_id我想申请一个Long,所以我怎么能以最简单的方式投出?该Client.apply语法是真棒它的简单,但我愿意像映射选项.谢谢!

cro*_*ies 11

找到了一个非常棒的方法来执行此操作,看起来像我在问题中链接的文档中缺少.

首先,拉进Play!格式: import play.api.data.format.Formats._

然后在定义Form映射时使用of[]语法

然后新的表单val将如下所示:

val clientForm = Form(
    mapping(
      "id" -> of[Long],
      "name" -> text(minLength = 4),
      "address" -> text(minLength = 4),
      "city" -> text(minLength = 2),
      "province" -> text(minLength = 2),
      "phone" -> optional(text),
      "email" -> optional(text),
      "account_id" -> of[Long]
    )(Client.apply)(Client.unapply)
  )
Run Code Online (Sandbox Code Playgroud)

更新:使用optional()

经过进一步的实验,我发现你可以of[]和Play 混合!optional满足您班级中定义的可选变量.

所以假设account_id上面是可选的......

"account_id" -> optional(of[Long])
Run Code Online (Sandbox Code Playgroud)


myy*_*yyk 7

之前的答案肯定有效,但最好只使用import play.api.data.Forms._因为你必须导入的内容为optionaltext.

所以你可以使用longNumber.

val clientForm = Form(
  mapping(
    "id" -> longNumber,
    "name" -> text(minLength = 4),
    "address" -> text(minLength = 4),
    "city" -> text(minLength = 2),
    "province" -> text(minLength = 2),
    "phone" -> optional(text),
    "email" -> optional(text),
    "account_id" -> optional(longNumber)
  )(Client.apply)(Client.unapply)
)
Run Code Online (Sandbox Code Playgroud)