How to handle long and different formats on Play! Scala form?

In my model, all associated Long accounts are not normal integers. However, when processing the Scala form in the new Play! 2.0 I can only confirm the number of Int on the form, not Long .

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

Take the following view:

 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) ) 

Where do you see account_id , I want to apply Long , since I can do this the easiest way? The syntax of Client.apply is awesome in its simplicity, but I am open to parameters like mapping. Thanks!

+8
scala forms
source share
2 answers

Found a really amazing way to do this, which looks like it’s missing from the documentation related to the question.

Pull the Play first! formats: import play.api.data.format.Formats._

Then, when defining the display of the form, use the syntax of[]

and then the new val view will look like this:

 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) ) 

Update: using optional ()

After further experimentation, I found that you can mix of[] with Play! optional to match the optional variables defined in your class.

Suppose account_id above is optional ...

 "account_id" -> optional(of[Long]) 
+11
source share

The previous answer definitely works, but it would be better to use what is in import play.api.data.Forms._ , since you already need to import it for optional and text .

Therefore, you can use 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) ) 
+7
source share

All Articles