Wednesday, December 5, 2012

Listing menu items from database to layout file

Hello

Please bear with my noobness, I am super new to CakePHP, and don't really understand it yet.

So, I was messing around with default.ctp, of course to make a layout for my site. I followed the Blog Tutorial, and I am planning to build my site on that. 
I'd like to add a navigation menu, which would look like this in plain HTML:
<div class='menubar'>
<div class='menuitems'><a href='url_to_that_page'>First Page</a></div>
<div class='menuitems'><a href='url_to_that_page2'>Second Page</a></div>
<div class='menuitems'><a href='url_to_that_page3'>Third Page</a></div>
<div class='menuitems'><a href='url_to_that_page4'>Fourth Page</a></div> 
</div> 

I saw that the layout file uses lots of CakePHP's built in function to add divs and links, and I'd like to make this myself as well.
I have the following code in my default.ctp file:

foreach ($menu as $Menu):
echo $this->Html->div('grid_12 menubar', $this->Html->div('menuitems grid_3', $this->Html->link($menu['Menu']['item'], array('controller' => 'Menu', 'action' => 'loadmenu'))));
endforeach;
unset ($menu);

If i'm right, this would list my 4 menu items from my MySQL database. (I didn't find a way to add multiple child items in the div() 'helper(?)', this is why I have choosen to do it this way)
So, from my experiences of the Blog tutorial I made a model named Menu.php:

class Menu extends AppMenu{
}

And i made a controller for that (MenuController.php)
(I actually don't understand a bit of this whole Model and Controller thing, even thought I read the CookBook and documentation.. guess it'll come in time)

class MenuController extends AppController{
public function loadmenu(){
$this->set('Menu', $this->Menu->find('all'));
}
}

Ok so i got all this, let's check how it works. Going to localhost/website/posts i find this:

Notice (8): Undefined variable: Menu [APP\View\Layouts\default.ctp, line 44]
Warning (2): Invalid argument supplied for foreach() [APP\View\Layouts\default.ctp, line 44]

If i understand right, it does not pass the variable Menu from MenuController to the layout file.
Could someone please explain me how to do this, and why it didn't work? Also, if you've got some free time, and could explain me (the simplest way) how models and controller work (with views), i'd be really thankful.

Thanks a lot folks,
Tristan

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP
 
---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com.
To unsubscribe from this group, send email to cake-php+unsubscribe@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php?hl=en.
 
 

No comments: