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:
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?
in Play 2.1
val p = Form( mapping( "top" -> default(number,42) )(CData.apply)(CData.unapply) ).bindFromRequest()
will do what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With