Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does grails pass arguments to controller methods?

Tags:

grails

In grails controller examples, I have seen save(Model modelInstance) and save(). I tried them both, both of them works. I imagine grails instantiates the modelInstance with the params. Is my assumption correct?

I also noticed in index(Integer max), does the param has to be named max? or any name would work as long as it is a number?

How does these passing of arguments work underneath?

like image 991
froi Avatar asked May 07 '14 07:05

froi


1 Answers

If you write a controller like this...

class MyController {
    def actionOne() {
        // your code here
    }

    def actionTwo(int max) {
        // your code here
    }

    def actionThree(SomeCommandObject co) {
        // your code here
    }
}

The Grails compiler will turn that in to something like this (not exactly this, but this describes effectively what is happening in a way that I think addresses your question)...

class MyController {
    def actionOne() {
        // Grails adds some code here to
        // do some stuff that the framework needs

        // your code here
    }

    // Grails generates this method...
    def actionTwo() {
        // the parameter doesn't have to be called
        // "max", it could be anything.
        int max = params.int('max')
        actionTwo(max)
    }

    def actionTwo(int max) {
        // Grails adds some code here to
        // do some stuff that the framework needs

        // your code here
    }

    // Grails generates this method...
    def actionThree() {
        def co = new SomeCommandObject()
        bindData co, params
        co.validate()
        actionThree(co)
    }

    def actionThree(SomeCommandObject co) {
        // Grails adds some code here to
        // do some stuff that the framework needs

        // your code here
    }
}

There is other stuff going on to do things like impose allowedMethods checks, impose error handling, etc.

I hope that helps.

like image 123
Jeff Scott Brown Avatar answered Nov 15 '22 12:11

Jeff Scott Brown