user3776556
user3776556

Reputation: 33

Pass value from grails controller to a class inside src/groovy

I have a Grails application. I want to use a value from Grails controller class (say MyController) inside a class in src/groovy/MyClass.groovy

How can I pass the value from Grails controller class to this class? I couldn't find anything relevant.

I tried this:

class MyController {
def name = "myapp"
}

Class MyClass{
def username = MyController.name
}

Please correct me . Thanks

Upvotes: 1

Views: 172

Answers (1)

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27220

It is hard to say for sure without knowing what you are doing but your probably want to pass the value as an argument to a method in MyClass and you probably don't want the value to be a field in the controller class.

class MyController {
    def someControllerAction() {
        def name = // I don't know where you are
                   // getting this value, but you got it from somewhere

        def mc = new MyClass()
        mc.someMethod(name)
        // ...
    }
}

class MyClass {
    def someMethod(String name) {
        // do whatever you want to do with the name
    }
}

Or you could pass the value as a constructor argument:

class MyController {
    def someControllerAction() {
        def name = // I don't know where you are
                   // getting this value, but you got it from somewhere

        def mc = new MyClass(name: name)
        // ...
    }
}

class MyClass {
    def name
}

I hope that helps.

Upvotes: 1

Related Questions