Reputation: 3
I am trying to use a common beforeUpdate
method by writing in BootStrap.groovy
.
def init = { servletContext ->
for (domainClass in grailsApplication.domainClasses) {
if(domainClass.clazz.simpleName == domainName){
domainClass.metaClass.beforeUpdate = {
println "i am here "
def dirtyPropertyNames = this.getDirtyPropertyNames()
println(dirtyPropertyNames)
if(dirtyPropertyNames != null && dirtyPropertyNames.size() > 0) {
for (dirtyPropertyName in dirtyPropertyNames) {
def oldValue = (this.getPersistentValue((dirtyPropertyName)))
def newValue = (this."${dirtyPropertyName}")
}
}
}
}
}
}
But I cannot use this.getdirtyPropertyNames()
as it gives an error.
groovy.lang.MissingMethodException: No signature of method:
If it's in the domain itself, this.getDirtyPropertyNames()
works fine.
I tried using domainClass.getDirtyPropertyNames()
too but it still gives an error.
I am using Grails 4.
Upvotes: 0
Views: 141
Reputation: 27255
I am not sure if you are asking how to accomplish what you want, or why you are getting the error you are getting.
If you want to know how to accomplish what you want, I would use an event listener instead of metaprogramming the method. There are lots of examples out there, https://github.com/jeffbrown/gorm-events-demo/blob/261f25652e5fead8563ed83f7903e52dfb37fb40/src/main/groovy/gorm/events/demo/listener/AuditListener.groovy#L22-L26 is one.
If you are asking why you are getting the error you are getting, the reason is this
references the instance of BootStrap
, not the instance of your domain class. If you really really want to use the dynamic metaprogramming approach (you shouldn't) then you can solve that particular part of the problem by referencing delegate
instead of this
.
I hope that helps.
Upvotes: 1