0

I'm creating a mixin to add to my controllers that has some basic utility functions. One of the functions I'd like to perform in the mixin is resolving errors to their string using the g.message taglib. Unfortunately, I can't seem to access the the GrailsApplication within my static mixin method.

How would I access the Grails taglibs from my mixin, or is there a better way to achieve what it is I'm doing -- sharing common code between all controllers?

Here's the code I'm running. I think the issue is how to access Grails tag libs in static methods:

            static def preparePostResponse(domainInstance) {

                    def grailsApplication = new User().domainClass.grailsApplication


                    def postResponse = new AjaxPostResponse(domainObject: domainInstance)

                    if (domainInstance.hasErrors()) {
                        g.eachError(bean: domainInstance) {
                            postResponse.errors."${it.field}" = g.message(error: it)
                        }
                        postResponse.success = false
                        postResponse.message = "There was an error"
                    }
                    else {
                        postResponse.success = true
                        postResponse.message = "Success"
                    }
                    return postResponse
                }
cdeszaq
  • 30,869
  • 25
  • 117
  • 173
John Gordon
  • 2,181
  • 5
  • 28
  • 47

1 Answers1

0

You can access grailsApplication from anywhere in your application using one of several techniques. The GrailsApplicationHolder has been deprecated, but Burt Beckwith has a couple of solutions in this blog posting.

Probably the easiest one is to pull it out of an existing Domain, like so:

class MyMixin {
    static myMethod() {
        def grailsApplication = new MyDomainClass().domainClass.grailsApplication
        // use it like normal here
    }
}

He has another method setting up the variables in BootStrap using metaClass here.


Alternatively, you can use the more involved but (I think) better technique in this blog post to create a dedicated class for accessing the application. This is nice if you are going to use it several places. I created a dedicated AppCtx class in my application that has getters for grailsApplication, config, etc. It's much cleaner to write it this way:

def foo = AppCtx.grailsApplication...
Community
  • 1
  • 1
OverZealous
  • 39,252
  • 15
  • 98
  • 100
  • I tried your suggestion, and the grailsApplication was accessible, but I started getting null pointer exceptions somewhere in the bowels of groovy. I think it might be related to using a g: tag, g:forEach, within a static method. I moved the method into the controller itself--still keeping it static-- and got this exception.` Apparent variable 'g' was found in a static scope but doesn't refer to a local variable`. Can I access the g: tags from a static method? – John Gordon Apr 30 '12 at 12:59