Controller for child CMS page


Silverstripe Version: 4.1

I have a cms page of type OurBusinesses. The url for the page in the cms is /why-us/our-businesses.

I need a controller for it as I need to pull 6 random data objects for it.

How can I have a controller for this page that renders the CMS page and allows me to pull the data objects?

I’ve done this already for a HomePage type with a HomePageController and it all just worked without routes etc.

This didn’t. I made a OurBusinessesController which I thought might get used due to the naming convention matching the type, it didn’t.

So I made a route: ‘why-us/our-businesses’: ‘OurBusinessesController’

and did a dev/build?flush

The output of ?debug_request is

Debug (line 261 of RequestHandler.php): Testing ‘$Action//$ID/$OtherID’ with ‘’ on OurBusinessesController

Debug (line 269 of RequestHandler.php): Rule ‘$Action//$ID/$OtherID’ matched to action ‘handleAction’ on OurBusinessesController. Latest request params: array ( ‘Action’ => NULL, ‘ID’ => NULL, ‘OtherID’ => NULL, )

Debug (line 185 of RequestHandler.php): Action not set; using default action method name ‘index’

The route seems to finds the controller okay but what now? I’m assuming I need to use the index method to pull out cms page by it’s url somehow?

The home page I mentioned before did nothing in the controller to render the page. It just did it. It only has a method (Businesses()) in the controller that gets called to get the random data objects. Used in a template with just $Businesses


You can just put the method to retrieve the dataobjects in your page class. You shouldn’t need a controller just for that if it’s a normal part of the SiteTree.

public function getBusinesses() {
  return MyDataObject()->get();  //Your dataobject logic here, of course

In the template you can then just do:

<% loop $Businesses %>
 <!-- Some stuff -->
<% end_loop %>

Unless I’ve missed the point of what you’re doing… in which case, let me know!


Perfect thanks mate. I thought it had to go in a controller.