CakePHP Menu Helper for Tree data

This is the MenuHelper I use in my CMS system. It is designed to work with data from the Tree behaviour or from any $model->find(‘threaded’) call. I use it to generate multi level CSS menus (that you see at the top of most websites), contextual menus (that you see in sidebars, showing the current page and its ‘branch’) and sitemaps – which let’s face it are basically often just the same as a top level menu but without the fancy stuff to make them pop out when you hover over them.

Prerequisites, history, overview

There are a couple of prerequisites here which may mean that this isn’t applicable for a lot of people. The helper is designed to deal with ‘page’ structures organised in simple /parent/child/grand-child format e.g.

/home
/about
/about/company-history
/about/company-history/gallery
/about/ethos
/about/vacancies
/news
/news/2009/jan
/news/2009/feb
/news/2009/mar
/contact
(etc.)

In my system I have a model ‘Article’ with Tree behaviour attached. So in the example above ‘ethos’ is a child of ‘about’. Some of these pages have real content, but others just act as place holders for other controllers / models – ‘news’ is a placeholder for the ‘News’ model. But all of them (even the placeholders) have other data attached like content for sidebars or meta information.

The helper will add a ‘selected-item’ class to the LI corresponding to the current page, and if it has any parents it will add a ‘selected’ class to each of those parent LIs too.

I create a full slug for each ‘Article’ on $model->save()

The helper operates in 2 modes ‘tree’ (which is default) and ‘context’
‘tree’ will produce a whole list of nested ULs – can be used to generate top level navigation (works well with things like suckerfish)
‘context’ will only produce nested ULs for the current branch

Using the example above if you were on the /about/ethos page and you wanted the navigation fragment in the sidebar you would use ‘context’
/about
/about/company-history
/about/company-history/gallery
/about/ethos
/about/vacancies

Database Fields

These are the default field names, they can be simply overridden to match your database schema.

Required Fields

  • name
  • slug_url

Optional Fields

  • title_for_navigation
  • redirect_url
  • redirect_target

Example ‘threaded’ data

[Article] => Array
                (
                    [name] => Find out about us
                    [slug_url] => /about-us
                    [title_for_navigation] => About Us
                    [redirect_url] => 
                    [redirect_target] => 
                    [lft] => 15
                    [id] => 105
                    [rght] => 24
                    [parent_id] => 
                )

            [children] => Array
                (
                    [0] => Array
                        (
                            [Article] => Array
                                (
                                    [name] => Philosophy
                                    [slug_url] => /about-us/philosophy
                                    [title_for_navigation] => 
                                    [redirect_url] => 
                                    [redirect_target] => 
                                    [lft] => 16
                                    [id] => 111
                                    [rght] => 21
                                    [parent_id] => 105
                                )
)))

Usage

Include the helper in your controller as usual.

In a view / element to generate complete menu


echo $menu->setup($menu_data, array('selected' => $this->here));

In a view / element to generate a context menu from the same data, set the class of the parent UL


echo $menu->setup($menu_data, array('selected' => $this->here, 'type' => 'context', 'menuClass' => 'context-menu'));

In a view / element to generate a sitemap from different data, let the helper know to use the ‘Sitemap’ model rather than the default ‘Article’ model and set the parent UL class.


$sitemap = new MenuHelper();
echo $sitemap->setup($data,  array('modelName' => 'Sitemap', 'menuClass' => 'sitemap'));

The Helper Code

Download the Helper

find('threaded');
 * More specifically it is designed to generate menus composed of nested ULs for use in CMS systems where all the URLs are pretty:
 * 	- naviagtion menus (usually at the top of the page)
 * 	- context menus (usually found at the side) and showing the links in the current branch
 * 	- sitemaps
 * 
 * Overview (A bit of history)
 * 
 * The helper is designed to deal with navigation / page structures organised in simple /parent/child/grand-child like structures
 * for instance:
 * 
 * /home
 * /about
 * /about/company-history
 * /about/company-history/gallery
 * /about/ethos
 * /about/vacancies
 * /news
 * /news/2009/jan
 * /news/2009/feb
 * /news/2009/mar
 * /contact
 * (etc.)
 * 
 * -------------------
 * URLs are generated in the model or controller not in the view / helper
 * -------------------
 * In the system from which this is taken, I create a full slug for each page on $model->save();
 * Some of the pages are actual pages of text and others are palceholders for content in other models
 * but they allow you do things like control the content of left / right columns, set default meta tags etc.
 * The purpose being to create really easy site structures with nice urls, the 
 * In the example above /home, /about etc. are all from a single model 'Article' which is my master model 
 * /news however is a placeholder for the 'News' model and /contact for the 'Contact' model
 * 
 *
 * 
 * Required Fields
 * ------------------
 * title / name (defaults to 'title')
 * page url (defaults to 'slug_url' e.g. /about/ethos)
 * 
 * Optional Fields
 * ------------------
 * title_for_navigation
 * redirect_url
 * redirect_target
 * 
 * Example data
 * ------------------
 * [Article] => Array
                (
                    [name] => Find out about us
                    [slug_url] => /about-us
                    [title_for_navigation] => About Us
                    [redirect_url] => 
                    [redirect_target] => 
                    [lft] => 15
                    [id] => 105
                    [rght] => 24
                    [parent_id] => 
                )

            [children] => Array
                (
                    [0] => Array
                        (
                            [Article] => Array
                                (
                                    [name] => Philosophy
                                    [slug_url] => /about-us/philosophy
                                    [title_for_navigation] => 
                                    [redirect_url] => 
                                    [redirect_target] => 
                                    [lft] => 16
                                    [id] => 111
                                    [rght] => 21
                                    [parent_id] => 105
                                )
 * 
 * 
 * 
 *
 * Usage:
 * 
 * Include the helper in your controller as usual.
 * 
 * The helper operates in 2 modes 'tree' (which is default) and 'context'
 * 'tree' will produce a whole list of nested Uls - can be used to generate top level navigation (works well with things like suckerfish)
 * 'context' will only produce nested ULs for the current branch
 * 
 * Using the example above if you were on the /about/ethos page and you wanted the navigation fragment in the sidebar you would use context
 * /about
 * /about/company-history
 * /about/company-history/gallery
 * /about/ethos
 * /about/vacancies
 * 
 * In a view / element to generate complete menu
 * echo $menu->setup($menu_data, array('selected' => $this->here));
 * 
 * In a view / element to generate a context menu from the same data, set the class of the parent UL
 * echo $menu->setup($menu_data, array('selected' => $this->here, 'type' => 'context', 'menuClass' => 'context-menu'));
 * 
 * 
 * In a view / element to generate a sitemap from different data, let the helper know to use the 'Sitemap' model rather than the default 'Article' model and set the parent UL class.
 * $sitemap = new MenuHelper();
 * echo $sitemap->setup($data,  array('modelName' => 'Sitemap', 'menuClass' => 'sitemap'));
 * 
 * Version Details
 * 
 * 1.0
 * + Initial release.
 */
class MenuHelper extends AppHelper {
		
	/**
	 * Current page in application
	 *
	 * @var string
	 */
	private $selected = '';
	
	/** Internal variable for the data
	 *
	 * @var array
	 */
	private $array = array();
	
	/**
	 * Default css class applied to the menu
	 *
	 * @var string
	 */
	private $menuClass = 'menu';
	
	/**
	 * Default DOM id applied to menu
	 *
	 * @var string
	 */
	private $menuId = 'top-menu';
	
	/**
	 * CSS class applied to the selected node and its parent nodes 
	 *
	 * @var string
	 */
	private $selectedClass = 'selected';
	
	/**
	 * CSS class applied to the exact selected node in the tree - in addition to $selectedClass
	 *
	 * @var unknown_type
	 */
	private $selectedClassItem = 'item-selected';
	
	/**
	 * Default Slug
	 *
	 * @var string
	 */
	private $defaultSlug = 'home';
	
	/**
	 * Type of menu to be generated:
	 * 'tree' - to generate a complete tree
	 * 'context' - to only render the specific barnch under the current page
	 *
	 * @var string
	 */
	private $type = 'tree';
	
	/**
	 * Model name used in $array e.g. $data[0]['Article']['name']
	 *
	 * @var string
	 */
	private $modelName = 'Article';
	
	/**
	 * Database column name - (i.e. a shorter version of the name / title for use only in naviagtion)
	 * e.g. A page called 'Welcome to the giant flea circus' 
	 * might be set to show up on navigation as 'home'
	 *
	 * @var string
	 */
	private $titleForNavigation = 'title_for_navigation';
	
	/**
	 * Database column name for title / name
	 * @var string
	 */
	private $title = 'name';
	
	/**
	 * Database column name for complete page slug e.g. /about/history/early-years
	 *
	 * @var string
	 */
	private $slugUrl = 'slug_url';
	
	/**
	 * Database column name for redirect_url for instance if /about/blog redirects to http://blog.somewebsite.com
	 *
	 * @var string
	 */
	private $redirectUrl = 'redirect_url';
	
	/**
	 * Target for redirect (see redirectUrl)
	 *
	 * @var string
	 */
	private $redirectTarget = 'redirect_target';
	
	/**
	 * Minumum number of items required to render a context menu
	 *
	 * @var int
	 */
	private $contextMinLength = 2;
	
	/**
	 * Internal Counter used in type: 'context'
	 *
	 * @var int
	 */
	private $li_count = 0;
	
	/**
	 * Internal flag to see if the page has been matched to an item
	 *
	 * @var bool
	 */
	private $matched = false;
	
	/**
	 * Internal counter
	 *
	 * @var int
	 */
	private $i = 0;
	
	/**
	 * Enter description here...
	 *
	 * @var unknown_type
	 */
	private $rootNode = '';
	
	function __construct(){
		
	}
	
	public function setOption($key, $value){
		$this->{$key} = $value;
	}
	
	public function getOption($key){
		return $this->{$key};
	}
	
	/**
	 * Setup the helper and return a string to echo
	 *
	 * @param array $array Data array containing the lists
	 * @param array $config Configuration variables to override the defaults
	 * @return string
	 */
	public function setup($array, $config = array()){

		// update and override the default variables 
		if(!empty($config)){
			foreach ($config as $key => $value) {
				$this->setOption($key, $value);
			}
		}
		
		// set the default slug selected if the current page does not match
		if($this->selected == '/'){
			$this->selected = $this->defaultSlug;
		}
		
		$this->array = $array;
		
		
		
		// get the root node of the selected tree if this a context menu
		if($this->type == 'context'){
			$this->rootNode = $this->getRootNode($this->selected);
		}
		
		$str = $this->buildMenu();
		
		// if the current page has matched one of the links in the tree
		// then get rid of the 'default_slected' placeholder
		if($this->matched == true){
			$str = str_replace('default_selected', '', $str);
		} else {
			$s = ' class="' . $this->selectedClass . '" ';
			$str = str_replace('default_selected', $s, $str);
		}
		
		// if this is a context menu, it looks daft if it only has 1 item 
		// if this is the case hide it
		if($this->type == 'context'){
			if($this->li_count < $this->contextMinLength){
				$str = '';
			}
		}
	
		
		return $this->output($str);	
		
	}
	/**
	 * Call the menu iterator method and if it returns a string warp it up in a UL
	 *
	 * @return string
	 */
	protected function buildMenu(){
		
		$str = $this->menuIterator($this->array);

		if($str != ''){
			$str = '
    ' . $str . '
'; } return $str; } /** * Explode a url slug and get the root page * * @param string $string * @return string */ protected function getRootNode($string){ $rootNode = ''; if($string != ''){ $node = explode('/', $string); // $node[0] will always be empty becuase the first char of $this->selected will always be '/' $rootNode = $node[1]; } return $rootNode; } /** * Recursive method to loop down through the data array building menus and sub menus * * @param array $array * @param int $depth * @return string */ protected function menuIterator($array){ $str = ''; $is_selected = false; foreach($array as $var){ $continue = true; $selected = ''; $sub = ''; if($this->type == 'context' && ($this->getRootNode($var[$this->modelName][$this->slugUrl]) != $this->rootNode)){ $continue = false; } if($continue == true){ // if this is the first list item set default_selected placeholder $default_selected = ''; if($this->i == 0){ $this->i = 1; $default_selected = 'default_selected'; } if(!empty($var['children'])){ $sub .= '
    '; $sub .= $this->menuIterator($var['children']); $sub .= '
'; } $p = strpos($this->selected, $var[$this->modelName][$this->slugUrl]); if($p === false){ } elseif($p == 0){ // this is the selected item or a parent node of the selected item $selected = ' class="' . $this->selectedClass . '" '; $is_selected = true; $this->matched = true; } if($this->selected == $var[$this->modelName][$this->slugUrl]){ // this is the exact selected item $selected = ' class="' . $this->selectedClass . ' ' . $this->selectedClassItem . '" '; } // keep track if this is a contextual menu if($this->type == 'context'){ $this->li_count++; } // Get the name / title to be used for the link text $name = $this->getName($var); // Get the URL / target for the link $url = $this->getUrl($var); $str .= '
  • '; $str .= '' . $name . ''; $str .= $sub; $str .= '
  • '; } } return $str; } /** * Look in the data and check if this is a straight url * or whether it is actually a redirect * * @param array $var * @return array */ protected function getUrl($var = null){ $url = array(); if(isset($var[$this->modelName][$this->redirectUrl]) && !empty($var[$this->modelName][$this->redirectUrl])){ $url['url'] = $var[$this->modelName][$this->redirectUrl]; if(isset($var[$this->modelName][$this->redirectTarget]) && !empty($var[$this->modelName][$this->redirectTarget])){ $url['target'] = ' target="' . $var[$this->modelName][$this->redirectTarget] . '" '; } } else { $url['url'] = $var[$this->modelName][$this->slugUrl]; $url['target'] = ''; } return $url; } /** * See if there is a title_for_navigation * * @param array $var * @return string */ protected function getName($var){ if(isset($var[$this->modelName][$this->titleForNavigation]) && !empty($var[$this->modelName][$this->titleForNavigation])){ $name = $var[$this->modelName][$this->titleForNavigation]; } else { $name = $var[$this->modelName][$this->title]; } return $name; } } ?>

    18 thoughts to “CakePHP Menu Helper for Tree data”

    1. Thank you for your helper, you save my time ;-)

      But I have question: how do you parse custom (live created) url/pass? You update router.php? Or you parsing new url in app_controller ?

      I have three ideas, but could not select better ;-)

    2. Hi Vlad

      Glad it has been helpful. I’m not sure entirely what you mean, as the way I think about menus tends to be that you already know the structure…

      I think what you are getting at is how do I includeroutes from other models in a sitemap. So here is my Sitemap controller:

       1,
                  'Sitemap.startdate <= ' => date('Y-m-d H:i:s'),
                  'Sitemap.name != ' => 'Template',
                  array('OR' => array(
                    array('Sitemap.enddate > ' => date('Y-m-d H:i:s')),
                    array('Sitemap.enddate IS NULL'),
                    array('Sitemap.enddate ' => '0000-00-00 00:00:00')
              )));
            
            $order = array();
            
            $fields = array('Sitemap.id', 'Sitemap.startdate', 'Sitemap.enddate','Sitemap.parent_id','Sitemap.lft', 'Sitemap.name', 'Sitemap.slug', 'Sitemap.slug_url', 'Sitemap.redirect_url', 'Sitemap.redirect_target');
            
            $data = $this->Sitemap->find('threaded', array('conditions' => $conditions, 'order' => $order, 'fields' => $fields));
            
            
            $p = ClassRegistry::init('Piece');
            
            $p = $p->sitemap();
            
            $pieces = $this->loop($p, '/articles', 'PieceCategory', 'title', 'Piece', 'name');
            
            
            
            $i = 0;
            foreach($data as $var){
              
              if($var['Sitemap']['slug'] == 'articles'){
                $data[$i]['children'] = $pieces;
                break;
              }
              $i++;  
            }
            
          return $data;
        }
      
      
        function index(){
          
          $data = $this->buildTree();
          
          $this->set('data', $data);
          
          
          
        }
      
        protected function loop($data, $slug_base, $model_name, $name = 'name', $sub_model_name = null, $sub_name = null){
          
          
          
          $pieces = array();
          $i = 0;
          foreach($data as $var){
            
            //pr($var);
            
            
            
            if($sub_model_name){
              // 1st loop
              $pieces[$i]['Sitemap']['name'] = $var[$model_name][$name];
              $pieces[$i]['Sitemap']['slug'] = $var['PieceCategory']['slug'];
              $pieces[$i]['Sitemap']['slug_url'] = $slug_base . '/' . $var['PieceCategory']['slug'];
              
              $subs = $this->loop($var[$sub_model_name], $pieces[$i]['Sitemap']['slug_url'], $sub_model_name, $sub_name);
              
              $pieces[$i]['children'] = $subs;
              
            } else {
              
              $pieces[$i]['Sitemap']['name'] = $var[$name];
              $pieces[$i]['Sitemap']['slug'] = $var['slug'];
              $pieces[$i]['Sitemap']['slug_url'] = $slug_base . '/' . $var['slug'];
            }
            
            $i++;
          }
          
          
          
          return $pieces;
        }
        
       
        
      }
      ?>
      

      This takes the normal menu structure and appends the routes for another model called ‘Piece’ onto it.

      Also here is the key bit of my routes.php:

      	Router::connect('(?!admin|maps|news|pages|contacts|pieces|sections|users)(.*)', array('controller' => 'articles', 'action' => 'view'));
      

      (In essence if the selected page is not in admin or maps or news or pages (etc.) then send it to articles view)

      Hope this helps. ;)

    3. Yes, it’s helps. Usefully ;-)

      Now I think about – how to nice way to integrated this helper in my CMS. End extend whis “/slug/*”

      I mean ( I hope my english not so bad and you can understand what I mean ;-):

      I want to show breadcrumb not only like:

      Home / Articles / Useful / Current article

      But, also, I want highlight menu (submenu) for current page

      Hom
      Article
      Useful* (slug: /useful/*) – and highlight this submenu for all included url:

      /useful
      /useful/view/45
      /useful/index/page:3
      etc….

    4. I think, I found bug in your helper (or, maybe, not ;-)

      if I use slug:
      news
      news_company

      When I need show menu, I got “selectedItem” for both urls (/news_company: highlight /news in menu & /news_company)

    5. Hi

      Sorry for not getting back to you – have been a little tied up the last week.

      Sounds very much like you have found a bug – so thanks for pointing it out – I’ll have a look at it. (y)

      I am assuming that you’ve had a go with the helper now and what you wrote in your 2nd comment you’ve sorted? Actually I meant to add a method for breadcrumbs and then forgot about it – but it’s something to add for sure.

      Please just add another comment if you have any other questions or suggestions – it’s always great to have people trying out things.

      Cheers

    6. Hi ;-)

      I add (just alpha-version) functionality like /news -> get index of news with paginate…
      So, when I try to get passed Args with router like you say (Router::connect(‘(?!admin|maps|news).

      I get urls like:

      http://tree.tt:8888/(?!admin)(.news/page:2)

      I don’t dig in route, but I think – it’s need to some change. ;)

    7. I can found only one (at present time) solution:
      Router::connect(‘/’, array(‘controller’ => ‘pages’, ‘action’ => ‘display’, ‘home’));
      Router::connect(‘/admin/:controller/:action/*’, array(‘controller’ => ‘posts’,’admin’ => true),array(‘pass’ => ‘controller’,’controller’ => ‘(posts|trees|types)’));
      Router::connect(‘/*’, array(‘controller’ => ‘posts’, ‘action’ => ‘view’));

    8. I’m wrong ;-( doesn’t work.

      Couldn’t found solution like your Router:connect but for nice paginate url…

    9. Hi Vlad

      No you are right – the trouble with the router hack (above) is that it breaks the pagination helper. If you can live with a controller stub /page/ then you don’t need the router hack.

      You can build custom routes to cover every instance but it would be a bit of a job… and I can’t think of an example of the top of my head.

      I extended the paginator helper to overload the link method like so:

      App::import('Paginator');
      class JpaginatorHelper extends PaginatorHelper {
      	
      var $passedArgs = null;
      
      
      /**
       * Extend the paginator helper and manually build the URL
       *
       * @param  string $title Title for the link.
       * @param  mixed $url Url for the action. See Router::url()
       * @param  array $options Options for the link. See #options for list of keys.
       * @return string A link with pagination parameters.
       */
      	function link($title, $url = array(), $options = array()) {
      		$options = array_merge(array('model' => null, 'escape' => true), $options);
      		$model = $options['model'];
      		unset($options['model']);
      
      		if (!empty($this->options)) {
      			$options = array_merge($this->options, $options);
      		}
      		if (isset($options['url'])) {
      			$url = array_merge((array)$options['url'], (array)$url);
      			unset($options['url']);
      		}
      		$url = $this->url($url, true, $model);
      		$obj = isset($options['update']) ? 'Ajax' : 'Html';
      		$url = array_merge(array('page' => $this->current($model)), $url);
      		$url = array_merge(Set::filter($url, true), array_intersect_key($url, array('plugin'=>true)));
      		
      		$str = '';
      		
      		foreach($this->passedArgs as $key => $value){
      			if(is_numeric($key)){
      			$str .= '/' . $value;
      			}
      		}
      		
      		$str .= '/page:' . $url['page'];
      
      		return $this->{$obj}->link($title, $str, $options);
      		
      	}
      }
      
      

      Example Usage:

      passedArgs = $this->passedArgs;
       echo $jpaginator->prev(__('Previous', true));?>
      
      numbers();?>
      next(__('Next', true));?>

      Basically it just builds the link normally and appends the page to the end – it will make sense if you compare it with the core pagination helper.

      J

      p.s. am working on an updated version of the helper.

    10. You can try also:

      Router::connect(‘/:promo’,array(‘controller’ => ‘posts’,’action’ => ‘view’),array(‘promo’ => ‘(?!(admin|posts|trees|types)\W+)[a-zA-Z\-_]+’));

      Paginator work fine (if you tell him paginator->option(‘url’ => ‘../../$$$$’)
      (where $$$$ = $this->passedArgs

    11. Thanks. Do you mean that’ll work with a standard paginator helper? I’ll give that a go when I get home.

      J

    12. 2John: every code need to test in your home lab ;-)

      $$$$ -> I mean no so ->passedArgs, but url :promo (from first string)
      ->option(‘url’ => ‘../../news’); (for url: http://test.tt://news/……..

    13. Hello, I’m trying to use the helper in context mode, but it give me this error: Undefined offset: 1 [APP/views/helpers/menu.php, line 353].
      Don’t show anything, in tree mode it show all the menu.

      Thanks for help!

    14. hi, this is great, thanks!

      More stuff that would be great:

      submenus – all the stuff below current item
      Limit depth – just show nth level of items – eg if you don’t want drop down in menus.

      Have you implemented either of those? Are you planning any further updates? Is it on github or anything?

      Thanks again,

      will

    15. Hi Will

      I’m glad that it has come in handy. I’m afraid that I haven’t done any new CakePHP development pretty much since I did built this (work going in different directions etc.)

      I do have a plan to put all my archive stuff up on Bitbucket (I prefer Mercurial to Git) – but realistically I’m so busy this will probably never happen :(

      On a kind of related note though I’ve just finished an extremely complex project which (excluding design work) a team of four of us put together in less than 2 weeks. We used Yii and none of us build a production site with it before. Can’t say it wasn’t extremely stressful, but overall it was a very positive experience – and it is a delight to work with.

    Comments are closed.