Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle Long and different formats in a Play! Scala form?

In my model all associated accounts are Long not normal integers. However, when handling the Scala form in the new Play! 2.0 I can only validate an Int number in a form and not a Long.

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

Take the following form:

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 you see account_id I want to apply a Long, so how could I cast that in the simplest way possible? The Client.apply syntax is awesome for its simplicity but I'm open to options like mapping. Thanks!

like image 961
crockpotveggies Avatar asked Mar 24 '12 23:03

crockpotveggies


2 Answers

Found a really awesome way to do this that looks like is missing from the documentation I linked in the question.

First, pull in Play! formats: import play.api.data.format.Formats._

Then when defining the Form mapping use of[] syntax

and then the new form val will look like:

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 discovered that you can mix of[] with the Play! optional to meet the optional variables defined in your class.

So assume that the account_id above is optional...

"account_id" -> optional(of[Long])
like image 150
crockpotveggies Avatar answered Nov 03 '22 00:11

crockpotveggies


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

So instead 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)
)
like image 35
myyk Avatar answered Nov 03 '22 00:11

myyk