tags:

views:

410

answers:

3

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?

A: 

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.

Jared
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).
knorv
+1  A: 

added a filter see the setion 5.5.1 Events and Auto Timestamping in the grails documentation (http://grails.org/doc/1.1.x/index.html)

   def beforeInsert = {
       if (price == '') { price = 0}
   }
Aaron Saunders
nice solution!!
Erik Ahlswede
Hi Aaron! Nice idea, but wouldn't the scaffolding layer complain before beforeInsert is reached?
knorv
That is - the scaffolding layer would complain because the domain object doesn't validate.
knorv
A: 

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;
        }
    })
}
Aaron Saunders