Search code examples
navigationhierarchypimcore

Adding Nested Links to a Pimcore 5 Navigation Menu


As per the Pimcore 5 documentation, you can manually add a navigation link to a menu using the following routine:

$home = Document::getById(1);

$navigation->addPage([
  'order' => -1, // put it in front of all the others
  'uri' => '/', //path to homepage
  'label' => $home->getProperty('navigation_name'), //visible label
  'title' => $home->getProperty('navigation_title'), //tooltip text
  'active' => $this->document->id == $home->id //active state
]);

However, what I've not been able to discern is how I can add a link to a navigation menu and define a parent link that the newly added link should be nested under.


Solution

  • I did some digging in the Pimcore 5 github repo:

    https://github.com/pimcore/pimcore/blob/master/pimcore/lib/Pimcore/Navigation/Page.php

    What I discovered is that when you add a page using the above prescribed method, you can include a pages entry in the array nested with the links you want to nest inside that link.

    For instance:

    <?php
    
      // Manually add navigation links
      // to a Pimcore\Navigation\Container object
      $NavigationContainer->addPage(
        // Add a top-level link at the front (order = -1)
        array(
          'order' => -1,
          'uri' => '/test',
          'label' => 'Test',
          'title' => 'Test',
          'pages' => array(
            // Add a secondary-level link...
            array(
              'order' => 0,
              'uri' => '/test/a',
              'label' => 'Test A',
              'title' => 'Test A',
              'pages' => array(
                // Add a tertiary-level link...
                array(
                  'order' => 0,
                  'uri' => '/test/a/1',
                  'label' => 'Test A1',
                  'title' => 'Test A1'
                ),
                // Add a tertiary-level link...
                array(
                  'order' => 1,
                  'uri' => '/test/a/2',
                  'label' => 'Test A2',
                  'title' => 'Test A2'
                )
              )
            ),
            // Add a secondary-level link...
            array(
              'order' => 0,
              'uri' => '/test/b',
              'label' => 'Test B',
              'title' => 'Test B'
            )
          )
        )
      );
    

    This will add the following to your navigation HTML, assuming you're not creating a custom render using a navigation partial:

    <li>
      <a title="Test" href="/test">Test</a>
      <ul>
        <li>
          <a title="Test A" href="/test/a">Test A</a>
          <ul>
            <li><a title="Test A1" href="/test/a/1">Test A1</a></li>
            <li><a title="Test A2" href="/test/a/2">Test A1</a></li>
          </ul>
        </li>
        <li><a title="Test B" href="/test/b">Test B</a></li>
      </ul>
    </li>