Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define default values optional fields in play framework forms?

I am implementing a web api using the scala 2.0.2 play framework. I would like to extract and validate a number of get parameters. And for this I am using a play "form" which allows me to define optional fields.

Problem: For those optional fields, I need to define a default value if the parameter is not passed. The code is intended to parse correctly these three use cases:

  • /test?top=abc (error, abc is not an integer)
  • /test?top=123 (valid, top is 123)
  • /test (valid, top is 42 (default value))

I have come up with the following code:

def test = Action {
  implicit request =>

  case class CData(top:Int)

  val p = Form(
    mapping(
      "top" -> optional(number)
    )((top) => CData($top.getOrElse(42))) ((cdata:CData) => Some(Some(cdata.top)))
  ).bindFromRequest()

  Ok("all done.")
}

The code works, but it's definitely not elegant. There is a lot of boiler plate going on just to set up a default value for a missing request parameter.

Can anyone suggest a cleaner and more coincise solution?

like image 360
natbusa Avatar asked Jul 07 '12 23:07

natbusa


1 Answers

in Play 2.1

val p = Form(
    mapping(
      "top" -> default(number,42)
    )(CData.apply)(CData.unapply)
  ).bindFromRequest()

will do what you want.

like image 73
rssh Avatar answered Oct 20 '22 20:10

rssh