After adding this to the end of my display function inside app/controllers/pages_controller.php,
// grab all message lists
$this->loadModel('MessageList');
$this->set('messageLists', $this->MessageList->find('all'));
I try to access it in app/views/pages/home.ctp like
<?php
foreach($messageLists as $messageList) {
print_r($messageList);
}
?>
But I get the warning
Notice (8): Undefined variable: messageLists [APP\views\pages\home.ctp, line 9]
My app/config/routes.php has:
/**
* Here, we are connecting '/' (base path) to controller called 'Pages',
* its action called 'display', and we pass a param to select the view file
* to use (in this case, /app/views/pages/home.ctp)...
*/
Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
/**
* ...and connect the rest of 'Pages' controller's urls.
*/
Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));
What do I need to change so that I can access $messageLists in my home page? Thanks!
At the very end of your display() method? Well this won’t work because its calling render() before and by this render the page before you set the view vars for it. So move your set() call before the render() call.
Also a further hint: Your implementation is not very well done except you want to cause additional queries on each page that does not even need to display the messages.
It looks like you’re a CakePHP beginner so I suggest you to lookup requestAction() in the manual and how elements in the views work. This would allow you to display the list of messages using an element in any view file by using an element and a request action to for example Messages/getListForUser.