Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a controller function for the "home" view in CakePHP

Tags:

cakephp

When visiting a default CakePHP site, it takes you to "home.ctp" page.

Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));

I want to add a few elements there (like blog posts), so I thought I could just add this to the PagesController() class:

public function home() {
    $this->set('blogposts', $this->Blogpost->find('all'));
}

But that does not work.

So: what is the correct way to add something like this on the home page (or any other page for that matter)

like image 842
John Avatar asked Dec 04 '25 22:12

John


2 Answers

The preferred option is to create a custom route for the home page but you can also override the PagesController's display function

Option 1: (Preferred Method)

Router::connect('/', array('controller' => 'mycontroller', 'action' => 'myaction'));

Option 2

Router::connect('/', array('controller' => 'pages', 'action' => 'home'));

Option 3:

class PagesController {
    function display()
    {
        // default controller code here
        // your custom code here
    }
}

The final option is using requestAction in your view, but it isn't recommended as it has a huge performance drawback

Option 4: (Not recommended)

$newsitems = $this->requestAction(array('controller' => 'newsitems', 'action' => 'getlatestnews', 'limit' => 10));
like image 189
Pierre Avatar answered Dec 07 '25 17:12

Pierre


In fact, the action is display, home is a parameter. So your main method in the Controller Pages must call display, not home. After that, create display.ctp view.

Reference:

  • Routing
like image 35
Paulo Rodrigues Avatar answered Dec 07 '25 16:12

Paulo Rodrigues