SalutBarbu
SalutBarbu

Reputation: 426

Access Silverstripe Page Requirements from a controller

I have a the following in mysite/code/Page.php:

...

class Page_Controller extends ContentController {

  public function init() {
    parent::init();
    Requirements::javascript("themes/example/js/global1.js");
    Requirements::javascript("themes/example/js/global2.js");
    Requirements::javascript("themes/example/js/global3.js");
  }
}

...

and then a custom controller in mysite/controllers/PlayController.php:

...

class PlayController extends ContentController {

  public function init() {
    parent::init();
    Requirements::javascript("themes/example/js/play.js");
  }
}

...

I would like to use the Requirements from Page.php in PlayController.php. Since they both extend ContentController, is this possible?

A little background; PlayController is used to display a page for a theatre play with the template Layout/PlayPage.ss. If I put the Requirements in templates/Page.ss, they are inherited by PlayPage.ss. But I'd like to put the Requirements in a controller, so I can use Silverstripe's combine_files feature. Hope this makes sense!

Thanks :-)

Upvotes: 0

Views: 68

Answers (1)

bummzack
bummzack

Reputation: 5875

You could create a subclass of ContentController that can serve as the base-class for both of your controllers. Eg. you create a MyController extends ContentController and then PlayController and Page_Controller extend MyController.

Or you could just require all the files in both controllers… if that's too much redundancy, you could also use the config API for this. Here's an example:

class Page_Controller extends ContentController 
{
  private static $js_requirements = [
    "themes/example/js/global1.js",
    "themes/example/js/global2.js",
    "themes/example/js/global3.js"
  ];

  public function init() {
    parent::init();
    foreach ($this->config()->js_requirements as $js) {
        Requirements::javascript($js);
    }
  }
}

And then in your PlayController, you could access the config of Page_Controller like so:

class PlayController extends ContentController 
{
  public function init() {
    parent::init();
    foreach (Config::inst()->get('Page_Controller', 'js_requirements') as $js) {
        Requirements::javascript($js);
    }
    Requirements::javascript("themes/example/js/play.js");
  }
}

You could then also use the YAML config to configure your requirements, eg.:

# mysite/_config/config.yml
Page_Controller:
  js_requirements:
    - "themes/example/js/global4.js"

Note: Always use dev/build, so that your config variables are being picked up.

Upvotes: 2

Related Questions