Set a menu - reusable code

3 followers

This wiki article has not been tagged with a corresponding Yii version yet.
Help us improve the wiki by updating the version information.

As we know Using crud generator creates menu items in view files (for each view file have a varius menu items)

In the case you want the same menu but diferrent active class for selected item ( Controller/action) you can create a function that set the menu and the active item.

For example in your controller

public function setMenu($mid) {
        $this->menu = array(
            array('active' => $mid === 'action-1', 'label' => Yii::t('default', 'my label1'), 'url' => array('action1')),
            array('active' => $mid === 'action-2', 'label' => Yii::t('default', 'my label2'), 'url' => array('action2')),
            array('active' => $mid === 'action-3', 'label' => Yii::t('default', 'my label3'), 'url' => array('action3')),
            array('active' => $mid === 'action-4', 'label' => Yii::t('default', 'my label4'), 'url' => array('action4')),
            array('active' => $mid === 'action-5', 'label' => Yii::t('default', 'my label5'), 'url' => array('action5')),
            array('active' => $mid === 'action-6', 'label' => Yii::t('default', 'my label6'), 'url' => array('action6')),
        );
    }

Now you can set the menu in easy way either in your action or in view file

$this->setMenu('action-3'); //set the action3 menu item to active

In addition using css class 'active' for the menu selector you can set different style for the acivated menu item

What are the advantages of that ?

a) reusable code b) small code c) easy maintenance especially for menu with a lot of items

Be the first person to leave a comment

Please to leave your comment.

Write new article