Mister Been Mister Been - 2 months ago 27
PHP Question

Creating breadcrumbs in symfony 2.1 using knpmenu bundle

What's the best way to create breadcrumbs using knpmenu bundle in symfony 2.1.x ? Aside from using 3-rd party bundles.

UPDATE:

Hi, theunraveler, sorry for late answer. Now I've been following your example and I'm stuck at one moment. Here, code below throws an exception, that

Missing argument 2 for Acme\DemoBundle\Menu\MenuBuilder::getBreadCrumbs()

{% set item = knp_menu_get('main') %}
{{ knp_menu_render(item) }}
{% block breadcrumbs %}
{% set breadcrumbs = knp_menu_get('breadcrumbs', [], {'request': app.request, 'menu': item }) %}
{{ dump(breadcrumbs) }}
{% endblock %}


Why it doesn't accepts "item" variable?

Answer

The Knp\Menu\MenuItem class has a getBreadcrumbsArray() method. It should return an array of items in the current active menu trail. If you are on an earlier version of KnpMenu (<= 1.1.2, I think), the returned array will be in the form of label => uri. Otherwise, it will be an array with each item having keys label, uri, and item.

To find the current menu item, you'll probably want to create a method in your controller (or somewhere else, if it makes more sense for your project) that looks something like this:

public function getCurrentMenuItem($menu)
{
    foreach ($menu as $item) {
        if ($item->isCurrent()) {
            return $item;
        }

        if ($item->getChildren() && $current_child = $this->getCurrentMenuItem($item)) {
            return $current_child;
        }
    }

    return null;
}

From there, you can call getBreadcrumbsArray() on the returned value:

$this->getCurrentMenuItem($your_menu)->getBreadcrumbsArray();

I guess what I would do ultimately is create a Twig extension that registers a breadcrumbs global, and put the getCurrentMenuItem() method in there. That way, you can have the breadcrumb variable in all of your templates without having to manually render it in each controller.

Source: https://github.com/KnpLabs/KnpMenu/blob/master/src/Knp/Menu/MenuItem.php#L544.

Comments