7

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.

Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
mrok
  • 2,680
  • 3
  • 27
  • 46

3 Answers3

18

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
    }
}
Kelly
  • 3,709
  • 4
  • 20
  • 31
  • Thanks, it works. Unfortunately grails.org is down, due to some routing problems http://grails.1312388.n4.nabble.com/Is-the-plugin-repository-down-td4628824i40.html so I needed ask here – mrok Jun 03 '12 at 20:45
  • The above solution is probably best, but another option is to use a grails calculated field. See the docs for that. – sf_jeff Jul 10 '14 at 18:52
  • 1
    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. – IgniteCoders Nov 03 '14 at 10:15
2
class Page {
    def beforeInsert() {
        this.beforeUpdate()
    }
    def beforeUpdate() {
        this.urlCrc = 'calculate something'
    }
}
IgniteCoders
  • 4,834
  • 3
  • 44
  • 62
1

This topic is covered in the GORM docs:

6.5 Advanced GORM Features

6.5.1 Events and Auto Timestamping

fergal_dd
  • 1,486
  • 2
  • 16
  • 27