korefn korefn - 1 month ago 13
Scala Question

Play Forms from case classes

I'm new to playframework. I have my model for a User as well as the accompanying object for the static methods...

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


I want to create a form for this class omitting some of the details. Currently I have a UserForm case class

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


To allow me to use:

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


This feels kind of
Hacker-ish
. Is there an idiomatic and more conscice way to do this?

Answer

How about

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

There are a lot more built-in checks and validations. The basics are listed here: http://www.playframework.com/documentation/2.1.0/ScalaForms

If you don't need them in an object you could use a tuple

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

The tuple in your case you have the following type: (String, String, String, String) which you could use like this: val (fullName, username, password, confirm) = refToTuple

Comments