24 July 2010

This tutorial shows how you can attach dynamic menu or any content to layout that you still want to call from controllers.

Making dynamic menus for layouts is not as to get hang on, but if you learn it then it seems logical and simple enough. Here are steps per files.


You need a simple model for this tutorial. I have my menu names in database so I will call those from there. Table name is "menus" and menu names are in column named "menu". Here is the code for my model:
Source code viewer
  1. <?php
  3. class Menu extends AppModel {
  4. var $name = 'Menu';
  5. }
  7. ?>
Programming Language: PHP


Controller returns array of menus to who ever is requesting this controller. Controller is in controllers folder and the name is menus_controller.php.
Source code viewer
  1. <?php
  2. class MenusController extends AppController {
  4. var $name = 'Menus';
  6. function index() {
  7. $menus = $this->paginate();
  8. return $menus;
  9. }
  10. }
  11. ?>
Programming Language: PHP


In views folder there is elements folder. This element goes in there. I called it to menu.ctp, contents of this file:
Source code viewer
  1. <?php
  2. //$menus equals with array of variables from database. You can give all sorts of parameters.
  3. $menus = $this->requestAction('menus/index/sort:menu/direction:asc');
  5. foreach ($menus as $menu) {
  6. echo '<h2>'.$menu['Menu']['menu'].'</h2>';
  7. }
  8. ?>
Programming Language: PHP


Here is one really basic layout. And we get the element to div thats id is "menu".
Source code viewer
  1. <?php echo $html->docType('xhtml-trans'); ?>
  4. <div id="header">
  5. Title<br />
  6. Slogan
  7. </div>
  8. <div id="layout">
  9. <div id="menu">
  10. <?php echo $this->element('menu'); ?>
  11. </div>
  12. <div id="content">
  13. <?php echo $content_for_layout; ?>
  14. </div>
  15. </div>
  16. <div id="footer">
  17. Copyright &copy; 2010 example.com - All Rights Reserved
  18. </div>
  19. </body></html>
Programming Language: HTML
And that's it. Dynamic content to layouts in CakePHP. You can make any dynamic data not just menus and it's not necessary to pull the menus from database as well. Though if it's static then there is no reason to include any controller. I saw one guy make the same thing using sessions and I thought that can't be right. Use sessions for holding content, so I thought that I need to write this tutorial.