M. F
M. F

Reputation: 87

How to addChild to special position (order) KNP Menu

Is there a way to addChild not on the end of the menu? If I have:

And I want add blue before Yellow?

$menu = $event->getMenu();
$menu->getChild('colors')
            ->addChild('blue', [
                'route' => 'blue_link',
            ])

Upvotes: 1

Views: 467

Answers (1)

M. F
M. F

Reputation: 87

If anybody needs help, this is the way:

use Knp\Menu\Util\MenuManipulator;

public function testMoveToPosition(): void
    {
        $menu = new MenuItem('root', new MenuFactory());
        $menu->addChild('c1');
        $menu->addChild('c2');
        $menu->addChild('c3');
        $menu->addChild('c4');

        $manipulator = new MenuManipulator();
        $manipulator->moveToPosition($menu['c1'], 2);
        $this->assertEquals(['c2', 'c3', 'c1', 'c4'], \array_keys($menu->getChildren()));
    }

Upvotes: 2

Related Questions