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

时间:2012-03-24 23:39:35

标签: 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)
  )

你看到account_id我要申请Long,我怎么能以最简单的方式投出? Client.apply语法因其简单性而非常棒,但我对映射等选项持开放态度。谢谢!

2 个答案:

答案 0 :(得分:11)

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

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

然后在定义表格映射时使用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)
  )

更新:使用optional()

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

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

"account_id" -> optional(of[Long])

答案 1 :(得分: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)
)