Grails - how execute code before every save?

12,728

Solution 1

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
    }
}

Solution 2

class Page {
    def beforeInsert() {
        this.beforeUpdate()
    }
    def beforeUpdate() {
        this.urlCrc = 'calculate something'
    }
}

Solution 3

This topic is covered in the GORM docs:

6.5 Advanced GORM Features

6.5.1 Events and Auto Timestamping

Share:
12,728
mrok
Author by

mrok

Updated on June 27, 2022

Comments

  • mrok
    mrok almost 2 years

    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.

  • mrok
    mrok almost 12 years
    Thanks, it works. Unfortunately grails.org is down, due to some routing problems grails.1312388.n4.nabble.com/… so I needed ask here
  • sf_jeff
    sf_jeff almost 10 years
    The above solution is probably best, but another option is to use a grails calculated field. See the docs for that.
  • IgniteCoders
    IgniteCoders over 9 years
    If you want to execute the code before the save use beforeUpdate() / beforeInsert(). if you use beforeValidate() that it's called always when you call validate() (method save() call 'validate()' before save). So your code it's executed before validate even if you don't save.
  • dopatraman
    dopatraman over 7 years
    can you link to the documentation on this?
  • IgniteCoders
    IgniteCoders over 7 years
    Yes, this is the documentation