Search code examples
grailsgrails-controller

How can I substitute my own custom dynamic scaffolding methods


My grails app has to define some additional behaviour for many of the standard dynamic scaffolding methods for each domain class.

I know I can duplicate the methods I need to add to for each controller, and indeed that is what I currently do. This does mean that my custom code is obscured by the boilerplate scaffolding.

I have tried importing and modifying the templates as well but they only seem to get involved if I generate static scaffolding in my controllers. Needless to say this doesn't help much.

Interceptors don't seem to be what I want either as they enclose the action rather than being inserted into it. I thought about intercepting the GORM call in some fashion but that isn't really what I want either.

What I really want to do is replace the base dynamic scaffolding methods with ones that have a hook in the places I want to be able to modify.

The following shows an example of what I am trying to achieve

    // standard "save" dynamic scaffold method decorated with hooks for custom code
    def save() {
        def ${propertyName} = new ${className}(params)

        saveBeforeSave(${propertyName})

        if (!${propertyName}.save(flush: true)) {
            render(view: "create", model: [${propertyName}: ${propertyName}])
            return
        }

        saveAfterSave(${propertyName})

        flash.message = message(code: 'default.created.message', args: [message(code: '${domainClass.propertyName}.label', default: '${className}'), ${propertyName}.id])
        redirect(action: "show", id: ${propertyName}.id)
    }

    // Placeholders hooks to be overridden in controller as necessary
    def saveBeforeSave(${propertyName}) {
    }
    def saveAfterSave(${propertyName}) {
    }

Solution

  • Can't you simple use the command:

    grails install-templates
    

    Then modify the controller ? Guide and Reference.

    Just configure your controller with

    static scaffold = *MODEL*
    

    and apply your modifications to /src/templates/scaffolding/Controller.groovy

    There is no need to generate to use generate-controller