Grails - how execute code before every save?
Asked Answered
K

3

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.

Kimmel answered 3/6, 2012 at 20:24 Comment(0)
E
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
    }
}
Eustazio answered 3/6, 2012 at 20:35 Comment(3)
Thanks, it works. Unfortunately grails.org is down, due to some routing problems grails.1312388.n4.nabble.com/… so I needed ask hereKimmel
The above solution is probably best, but another option is to use a grails calculated field. See the docs for that.Dirty
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.Licentiate
L
2
class Page {
    def beforeInsert() {
        this.beforeUpdate()
    }
    def beforeUpdate() {
        this.urlCrc = 'calculate something'
    }
}
Licentiate answered 3/11, 2014 at 10:20 Comment(2)
can you link to the documentation on this?Menendez
Yes, this is the documentationLicentiate
J
1

This topic is covered in the GORM docs:

6.5 Advanced GORM Features

6.5.1 Events and Auto Timestamping

Japan answered 23/3, 2015 at 18:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.