Search code examples
symfony1doctrinenested-setsdoctrine-1.2

Breadcrumb navigation with Doctrine NestedSet


I have a model that implements NestedSet behaviour:

Page:
  actAs:
    NestedSet:
      hasManyRoots: true
      rootColumnName: root_id
  columns:
    slug: string(255)
    name: string(255)

Example fixtures:

Page:
  NestedSet: true
  Page_1:
    slug: slug1
    name: name1
  Page_2:
    slug: slug2
    name: name2
    children:
      Page_3:
        slug: page3
        name: name3

I am looking for the easiest way to implement breadcrumb navigation (trail). For example, for Page_3 navigation will look like this:

<a href="page2">name2</a> > <a href="page2/page3>name3</a>

Solution

  • Almost the same as in the other question, but you have to add a 'parentUrl' variable :

    //module/templates/_breadcrumbElement.php
    foreach ($node->get('__children') as $child) :
      if ($child->isAncestorOf($pageNode)):
         $currentNodeUrl = $parentUrl . $child->getSlug() . '/';
         echo link_to($child->getName(), $currentNodeUrl) . ' > ' ;
         include_partial('module/breadcrumbElement', array('node' => $child, 'pageNode' => $pageNode, 'parentUrl' => $currentNodeUrl));
      endif;
    endforeach;
    

    Feed it the root of your tree as $node (hydrate it hierarchically), the node of the current page as $pageNode, and '' as $currentNodeUrl and add ' > ' and the link to the current page.

    Why does this solution use recursion and not getAncestors()? Because your urls seem to imply recursion.