Reputation: 570
I am currently using Grails-2.2.4, I would like to modify the behaviour of my domain mapping from bootstrap to alter the dateCreated Field to custom date. While trying to pull the mapping of domain to modify the autotimestamp behaviour, the GrailsDomainBinder.getMapping is returning null. Am I missing something, here is my code
grailsApplication.domainClasses.each { gdc ->
def domClass = gdc.clazz
def grailsSave = domClass.metaClass.pickMethod('save', [Map] as Class[])
domClass.metaClass.save = { Map params ->
def m = GrailsDomainBinder.getMapping(domClass.class)
println("The mapping ===>>>$m") /* **this gives Null** */
m.autoTimestamp = false
def colList = []
domClass.declaredFields.each{
if(!it.synthetic)
colList.add(it.name.toString())
}
if(colList.contains("dateCreated")) {
println(domClass.metaClass.getProperty(delegate,"dateCreated"));
domClass.metaClass.setProperty(delegate,"dateCreated",new Date("11/5/1990"))
grailsSave.invoke(delegate, [params] as Object[])
}
//...
}
}
I am getting an error
Cannot set property 'autoTimestamp' on null object
Upvotes: 3
Views: 279
Reputation: 570
I found out what I was doing wrong, the domain object returned from the domainClasses.clazz was not returning a GrailsDomainClass but default java class object which is not what it needed. Using delegate instead of domClass worked. Here is the working code cheers :) ..
grailsApplication.domainClasses.each { gdc ->
def domClass = gdc.clazz
def grailsSave = domClass.metaClass.pickMethod('save', [Map] as Class[])
domClass.metaClass.save = { Map params ->
def m = GrailsDomainBinder.getMapping(delegate.getDomainClass())
println("The mapping ===>>>$m")
m.autoTimestamp = false
def colList = []
domClass.declaredFields.each{
if(!it.synthetic)
colList.add(it.name.toString())
}
if(colList.contains("dateCreated")) {
println(domClass.metaClass.getProperty(delegate,"dateCreated"));
domClass.metaClass.setProperty(delegate,"dateCreated",new Date("11/5/1990"))
grailsSave.invoke(delegate, [params] as Object[])
}
//...
}
}
Upvotes: 3