从案例类播放表单

时间:2013-02-28 13:43:02

标签: scala playframework-2.0

我是playframework的新手。我有一个用户的模型以及静态方法的附带对象......

case class User(id: Int, username: String, password: String, fullname: String, /
     lastLogin : Date, updatedOn: Date, updatedBy: Int, createdOn: Date, createdBy: Int)

我想为这个类创建一个表单,省略一些细节。目前我有一个UserForm案例类

case class UserForm(fullName:String, username: String, password:String, confirm:String)

允许我使用:

val userForm = Form(
    mapping(
        "fullName" -> of[String],
        "username" -> of[String],
        "password" -> of[String],
        "confirm" -> of[String]
    )(UserForm.apply)(UserForm.unapply)
)

这感觉有点Hacker-ish。是否有一种惯用且更加便利的方法来做到这一点?

2 个答案:

答案 0 :(得分:3)

怎么样

val userForm = Form(
  mapping(
      "fullName" -> text,
      "username" -> text,
      "password" -> text,
      "confirm" -> text
  )(UserForm.apply)(UserForm.unapply)
)

还有更多内置的检查和验证。这里列出了基础知识:http://www.playframework.com/documentation/2.1.0/ScalaForms

如果你在对象中不需要它们,你可以使用元组

val userForm = Form(
  tuple(
      "fullName" -> text,
      "username" -> text,
      "password" -> text,
      "confirm" -> text
  )
)

在您的情况下,您有以下类型的元组:(String, String, String, String)您可以这样使用:val (fullName, username, password, confirm) = refToTuple

答案 1 :(得分:3)

迟到了,但我刚刚发布了一个实用程序来帮助解决这个问题!使用您的类,您的代码将如下所示:

case class User(id: Int, username: String, password: String, fullname: String, lastLogin : Date, updatedOn: Date, updatedBy: Int, createdOn: Date, createdBy: Int)
object User { implicit val mapping = CaseClassMapping.mapping[User] }

val userForm = Form(implicitly[Mapping[User]])

您可以在github上找到将其包含在项目中的来源和说明:https://github.com/Iterable/iterable-play-utils