D
D
Dmitry Kim2017-04-18 06:39:10
Yii
Dmitry Kim, 2017-04-18 06:39:10

How do I know if the requested action is in the controller?

The site has a main menu. There are links in the menu. Everything seems to be simple, because everyone has it.
To highlight the active menu item, a check is used:

$liCssClass = Yii::$app->controller->id == 'news' ? 'menu-item-active' : 'menu-item';

And further: For the general case, I need to store menu items in the database and, when requested, parse the url of the link and highlight the active menu item automatically. For this I write the code:
<li class="<?php echo $liCssClass ?>">Новости</li>
$currentController = \Yii::$app->controller;
$currentAction     = $currentController->action;
foreach($links as $link){
    list($controller, $actionId) = \Yii::$app->createController($link->url);
    if ($controller && $actionId) {
        if ($currentController->id == $controller && $actionId == $currentAction->id){
            $cssClass = 'menu-item-active';
        }
        else {
            $cssClass = 'menu-item';
        }
        $ul[] = Html::tag('li', $link->title, ['class' => $cssClass]);
    }
}

The catch is that it $controllercan return false, or $actionIdit can be absent in $controller(after all, links are taken from the database, and there you can make a mistake and insert a broken link).
How to check it? Is this code enough: $controller->hasMethod('action'.$actionId), or is it shit code?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question