I often write something like:
def myAction{ MyActionCommand cmd ->
if( cmd.hasErrors() ){
return render(status:HttpServletResponse.SC_BAD_REQUEST );
}else{
// actual action logic
}
So, I'd like to extract that common pattern into some reusable location. Filter looks like good candidate, but I can't find the way to get command object from the filter. Tryed something like this (in filters closure):
formValidation( controller:'*', action:'*' ){
before = { cmd ->
if( cmd.hasErrors() ){
response.sendError( HttpServletResponse.SC_BAD_REQUEST );
return false;
}else{
return true;
}
}
}
Intersted in grails 1.3.7 compatible solution. Is it possible at all?
No, it isn't possible to do what you are asking. Command Objects are not full framework artifacts like Controller, Service, etc, and so they do not get their validation logic added to them, unless they are a parameter to a Controller action. To that end a Command Object in a filter wouldn't have a
.validate()
or.hasErrors()
method to check against.As another option you could use the
@Validateable
annotation:http://grails.org/doc/latest/guide/7.%20Validation.html#7.5%20Validation%20Non%20Domain%20and%20Command%20Object%20Classes
Move your Command Object to
src/groovy
as a regular Groovy class and annotate it with@Validateable
. Then in your filter you can do:Make sure you add the package name of your validateable class to the
grails.validateable.packages
List in Config.groovy.What about creating a service like this:
The use it like so: