1

I have forms where I want to be able to leave some numerical fields empty, but I get "Invalid value" errors from Form.bindFromRequest(). This seems like a common requirement, but I can't find any documentation on this after hours of searching. I am still hoping I've missed something obvious, though!

I did some digging and found that Play uses Spring's DataBinder class to do the actual binding. That class is really sophisticated and would allow me to set custom binders for my fields, and if I was using Spring I could just add an @InitBinder method to my controller to set up the binder exactly the way I want using a CustomNumberEditor. However, it seems that Play Framework's Form object does not allow access to the DataBinder, apart from setting allowed fields. So, the binder tries to convert an empty string into a long, which gives a NumberFormatException:

Failed to convert property value of type 'java.lang.String' to required type 'long' 
for property 'unitPriceExVAT'; 
nested exception is java.lang.NumberFormatException: For input string: ""

So, is there some other way of getting the binder to allow empty numerical fields?

Rolf Staflin
  • 2,092
  • 2
  • 22
  • 19

1 Answers1

1

Declare your fields as Long instead of the long primitive type and the empty values will be treated as null.

estmatic
  • 3,449
  • 1
  • 19
  • 28
  • Haha, amazing :). I knew it couldn't be as complicated as I was making it! Case errors like that are nearly impossible to find on your own sometimes. Thanks for helping out – it worked perfectly of course! – Rolf Staflin Mar 07 '13 at 07:47