I'm new to Play !, and I'm trying to migrate my existing website from cakePHP to Play !.
The problem I am facing is form validation.
I have defined a case User class representing users of my website:
case class User( val id: Long, val username: String, val password: String, val email: String val created: Date)
(There are a few more fields, but these are enough to explain my problem)
I want my users to be able to create an account on my website using the form, and I would like this form to be validated on Play !.
So, I created the following action:
def register = Action { implicit request => val userForm = Form( mapping( "id" -> longNumber, "username" -> nonEmptyText(8), "password" -> nonEmptyText(5), "email" -> email, "created" -> date)(User.apply)(User.unapply)) val processedForm = userForm.bindFromRequest processedForm.fold(hasErrors => BadRequest("Invalid submission"), success => { Ok("Account registered.") }) }
Obviously, I do not want the user to fill in the identifier or creation date on the form. So my question is: what should I do?
Should I define a new "transition model" containing only those fields that are actually provided to the user in the form, and convert this intermediate model to the full one before inserting it into my database?
That is, replace my action with something like this:
def register = Action { implicit request => case class UserRegister( username: String, password: String, email: String) val userForm = Form( mapping( "username" -> nonEmptyText(8), "password" -> nonEmptyText(8), "email" -> email)(UserRegister.apply)(UserRegister.unapply) val processedForm = userForm.bindFromRequest processedForm.fold(hasErrors => BadRequest("Invalid submission"), success => { val user = User(nextID, success.username, success.password, success.email, new Date())
Or is there another, cleaner way to do what I want?
I went through a lot of tutorials and the book "Play for Scala", but in the only examples I found, the models were completely filled with forms ... I really like Play! still, but it looks like the documentation often lacks examples ...
Thanks so much for your answers!