Making Grails data-binding interpret empty String values (“”) as zero (0)

Tag: grails Author: he_zj0898 Date: 2009-08-31

This question is about altering how the Grails data-binding handles string-to-integer conversion.

Consider the following domain object:

class Foo {
  String name
  Integer price

Furthermore, assume that the domain object is populated from HTTP request parameters:

def foo = new Foo(params).save()

The save() method above will fail if params.price == "" (empty string). I'd like to change this behaviour globally so that an empty string is parsed as zero (0) when converting from a string to an integer in Grails data-binding. How do I achieve that?

Best Answer

added a filter see the setion 5.5.1 Events and Auto Timestamping in the grails documentation (

   def beforeInsert = {
       if (price == '') { price = 0}


nice solution!!
Hi Aaron! Nice idea, but wouldn't the scaffolding layer complain before beforeInsert is reached?
That is - the scaffolding layer would complain because the domain object doesn't validate.

Other Answer1

Instead of changing the data binding why not just write your own setter? In the setter test to see if the string is empty, if it is set price to 0. If it isn't do a normal integer conversion.


Hi Jared! Thanks for your input. I evaluated that option (changing domain classes), but while that would work it violates the DRY-principle since I would have to add that logic in a lot of places (there are quite some domain classes in the project).

Other Answer2

try this constraint instead

static constraints = {
    price(validator: {val, obj ->
        if (val == '' || val == 0) {
            obj.price = 0
            return true
        } else if (val < 1) {
            return false;