In our custom listener, the method ‘onPersistenceEvent’ is called on all GORM events that we filter to what we interested – PreInsert, PreUpdate
Create a groovy file under src/groovy suppose named 'FieldValidationListener.groovy' with the following contents. And create required method in your domain class, suppose one method can be named: 'doValidationPreInsert' or 'doValidationPreUpdate'.
package com.groovy.fieldSetting
import grails.util.Holders
import org.codehaus.groovy.grails.commons.GrailsApplication
import org.grails.datastore.mapping.core.Datastore
import org.grails.datastore.mapping.engine.event.*
import org.springframework.context.ApplicationEvent
/**
* Created by pritom on 17/02/14.
*/
class FieldValidationListener extends AbstractPersistenceEventListener {
public FieldValidationListener(Datastore datastore) {
super(datastore)
}
@Override
protected void onPersistenceEvent(AbstractPersistenceEvent event) {
String operation;
switch (event.eventType) {
case EventType.PreInsert:
operation = "PreInsert"
break;
case EventType.PreUpdate:
operation = "PreUpdate"
break;
}
if(operation) {
String methodName = "doValidation${operation}"
println "Searching for method: ${methodName}"
if (event.entityObject.respondsTo(methodName)) {
try {
event.entityObject."${methodName}"()
} catch (Exception exp) {
event.cancel();
throw exp;
}
}
}
}
@Override
boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
if ([PreInsertEvent, PreUpdateEvent].any { def supportedType ->
if (supportedType.isAssignableFrom(eventType)) {
return true
} else {
return false
}
}) {
return true
} else {
return false
}
}
public static void initialize(GrailsApplication application) {
application.mainContext.eventTriggeringInterceptor.datastores.each { k, datastore ->
Holders.applicationContext.addApplicationListener(new FieldValidationListener(datastore))
}
}
}
And initialize start listening, insert the following code block into 'BootStrap.groovy' [in 'init' method]:
FieldValidationListener.initialize(grailsApplication)