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
Author by
mrok
Updated on June 27, 2022Comments
-
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 thesave()
method is called. I cannot just override save method because it is injected. -
mrok almost 12 yearsThanks, it works. Unfortunately grails.org is down, due to some routing problems grails.1312388.n4.nabble.com/… so I needed ask here
-
sf_jeff almost 10 yearsThe above solution is probably best, but another option is to use a grails calculated field. See the docs for that.
-
IgniteCoders over 9 yearsIf you want to execute the code before the save use
beforeUpdate() / beforeInsert()
. if you usebeforeValidate()
that it's called always when you callvalidate()
(methodsave()
call 'validate()' before save). So your code it's executed before validate even if you don't save. -
dopatraman over 7 yearscan you link to the documentation on this?
-
IgniteCoders over 7 yearsYes, this is the documentation