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

Posted by natalinobusa on Stack Overflow See other posts from Stack Overflow or by natalinobusa
Published on 2012-07-07T23:49:29Z Indexed on 2012/07/08 9:16 UTC
Read the original article Hit count: 205

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?

© Stack Overflow or respective owner

Related posts about scala

Related posts about playframework