Question

I am trying to understand how Grails 2.3.4 generated scaffolding methods perform validation. For instance this is what was generated for my Club domain save method:

def save(Club clubInstance) {
    if (clubInstance == null) {
        notFound()
        return
    }

    if (clubInstance.hasErrors()) {
        respond clubInstance.errors, view:'create'
        return
    }

    clubInstance.save flush:true

    request.withFormat {
        form {
            flash.message = message(code: 'default.created.message', args: [message(code: 'clubInstance.label', default: 'Club'), clubInstance.id])
            redirect clubInstance
        }
        '*' { respond clubInstance, [status: CREATED] }
    }
}

From what I understand the first phase of validation happened upon the data binding to the Club clubinstance parameter of the save action. So any data binding errors will be caught on the if (clubInstance.hasErrors()).

I see no explicit call to clubInstance.validate() or any error check on clubInstance.save as the documentation suggests. It does seem to work however. So how does this method validate and return back to the view if there are constraint violations?

More importantly should we not be using the generated scaffolding controllers as the best practice way to do basic CRUD in Grails?

Was it helpful?

Solution

When you include parameters in controller action methods, Grails will do databinding for them. For simple types like Strings, numbers, Boolean, etc. the parameter name is matched against the param names and if there's a match and a sensible way to convert the param string to the requested type, it's done for you.

For complex types, the parameter is treated as a command object. If it's defined in the controller class it's made validateable at compile time via an AST transformation. If the class is defined elsewhere (e.g. src/groovy) it has to be annotated with the grails.validation.Validateable annotation, and if it's a domain class then it's obviously validateable. In any case, after the instance is created and data-bound, validate() is called for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top