Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a Groovy trait in a Grails controller

Tags:

grails

groovy

I would like to make use of a Groovy trait in a Grails controller as per the following:

trait ColumnSelectionController {
    def selectColumns() {
        //Do something here
    }
}

class MyController implements ColumnSelectionController {
    def index() {
        //Calculate list model
    }
}

When I run this in Grails however, the "selectColumns" action is not visible and I get a 404 response from Grails. I suspect that there is something that I need to do to the trait such that the methods defined inside of it are recognized as actions in the implementing class. Anybody know what that might be?

EDIT 1:

Further information: the trait is defined in src/groovy, not in grails-app/controllers, therefore it isn't defined as an Artefact.

EDIT 2:

In addition, if I change the trait to a class, mark it with the @Artefact annotation and change MyController to extend this class, everything works as expected. Attempting to use the @Artefact annotation on the trait does nothing (no big surprise).

like image 588
Steve Hole Avatar asked Mar 04 '15 17:03

Steve Hole


1 Answers

Just define @Action annotation over defined method in trait, this will make this method working as Action for controller(when traits get implemented)

import grails.web.Action

trait ColumnSelectionController {

  @Action
  def selectColumns() {
     //Do something here
  }
}

Hope this helps.

like image 139
Anshul Avatar answered Sep 17 '22 12:09

Anshul