Menu widget - Set active item?


Have question about the menu widget from Yii2. I have a menu generated with this widget. Menu items are generated and I see a nice menu. I have friendly urls enabled in the config and I hide the script name.

When i add a url to the nav link for instance /news/index and I select that menu item, I see that the nav sets the class I have set with the activeCssClass property. However, when I edit an item and I go to the url /news/update/3 the menu item is no longer selected. Even with "activateItems" and "activateParents" both set to true. Also, when I go to /news the menu item is not selected.

Can someone tell me, how I can set a menu item always active based on my controller name? I want the menu item news active as long as I am in /news/index or /news/update/1 or /news/new, etc. etc.

Can you show me your menu code ?

This is my code:

        foreach ($controllers as $controller) {

                $navItems[] = ['label' => Yii::t('backend',$controller->name), 'url' => ['/'.$controller->controller.'/index']];


        $this->output = Menu::widget(


                'activateItems' => true,

                'activateParents' => true,

                'activeCssClass' => 'active',

                'encodeLabels' => false,

                'options' => ['class' => 'sidebar-menu'],

                'items' => $navItems,



The output is printed later on.

This is a javascript function to active links which have the same controller

//File web/js/site.js

function menuActive($controller)


    //All links begining with the controller parameter

    $selector = $('a[href'+'^="/'+$controller+'"]').addClass('active');


Maybe you can use it. I didn’t test it.

In your Controller, active all links which have the same controller ID :

public function beforeAction($action) {


  return parent::beforeAction($action);


Hmmm ok. Seem like the menu widget is not advanced enough to it on it’s own. That’s too bad. :frowning: Will give your code a try. Thanks.

I solved this by extend yii\bootstrap\Nav class and change isItemActive method:

if (\yii\helpers\StringHelper::startsWith($this->route, ltrim($route, '/'))) {
    return true;
if (ltrim($route, '/') !== $this->route) {
    return false;