Grails domain classes has beforeInsert and beforeUpdate method that get fired before domain object is going to saved or updated respectively.
class Person { def securityService String name Date signupDate String lastUpdatedBy def beforeInsert() { signupDate = new Date() } def beforeUpdate() { lastUpdatedBy = securityService.currentAuthenticatedUsername() } }
Now whenever Person object is going to saved beforeInsert method is executed and signupDate is filled with current date and when ever Person object is going to update beforeUpdate method is executed and lastUpdatedBy is filled with current logged in user.
Every domain class have its own beforeInsert and beforeUpdate method. But if you want to perform some action before inserting or updating any domain object then you can set global beforeInsert and beforeUpdate methods in the BootStrap.groovy.
import org.codehaus.groovy.grails.commons.GrailsDomainClass class BootStrap { def init = { servletContext -> grailsApplication.domainClasses.each{ GrailsDomainClass gdc -> gdc.metaClass.beforeInsert = { log.debug "beforeInsert" //code here } gdc.metaClass.beforeUpdate = { log.debug "beforeUpdate" //code here } } } def destroy = {} }
Recent Comments