Grails - how execute code before every save?

mrok picture mrok · Jun 3, 2012 · Viewed 12.4k times · Source

Is there a good/standard way to execute some common code before every save() invocation on domain classes?

For example, my domain

class Page {

    String url
    Boolean processed
    Date date
    Integer urlCrc 
}

My form has only 3 first fields and I would like to calculate urlCrc every time the save() method is called. I cannot just override save method because it is injected.

Answer

Kelly picture Kelly · Jun 3, 2012

You can use GORM events - see the docs. Since by default validate() is called before every save() I would use that.

class Page {
    //your defs here

    def beforeValidate() {
        this.urlCrc = yourComputationHere
    }
}