Saturday, December 18, 2010

Grails T'n'T: Accessing current controller from a command object

Hi there folks!

This time we're going to talk about how to access the current controller instance from anywhere in the code. We're going to demonstrate this by the Command object example.

Imagine you're in a command object's method and want to call the render method. All would be nice and dandy if it'd be the controller itself but it turns out the command object is more like a domain class (with its ability to verify field values and so on) than anything else. But... there's hope!

Let's add the following method to our command object:
private getController() {
RequestContextHolder.
requestAttributes.
request.
getAttribute(GrailsApplicationAttributes.CONTROLLER)
}

This way we get a read-only property called controller that we can use to call the render method.

But there's more!

Imagine you'd like to access the current request, response or session from the command object. All you need to do is to get there via the controller:
controller.session
controller.request
controller.response

Even the params element of the controller is available!

I sure hope this will help you out in refactoring your code from the controller into external classes like the command objects.

Have fun!

No comments: