Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 Get current action in controller

Tags:

yii2

How can I get current action?

This code:

if (!Yii::$app->controller->action->id == 'lang') {
    Url::remember();
}

returns an error:

PHP Notice – yii\base\ErrorException

Trying to get property of non-object

like image 576
Dmitry Petrik Avatar asked Feb 06 '15 05:02

Dmitry Petrik


Video Answer


2 Answers

You should use beforeAction() event instead of init().

Also you can simply use $this because it contains current controller.

public function beforeAction($action)
{
    if (parent::beforeAction($action)) {
        if ($this->action->id == 'lang') {
            Url::remember();
        }

        return true; // or false if needed
    } else {
        return false;
    }
}
like image 110
arogachev Avatar answered Oct 18 '22 15:10

arogachev


You can get current action name by:

Yii::$app->controller->action->id

And get the controller name with this one:

 Yii::$app->controller->id;

Note: Remember that these will only work after the application has been initialized. Possible use: inside a controller action/ inside a model or inside a view

Reference: Class yii\web\Controller

like image 41
Imtiaz Avatar answered Oct 18 '22 15:10

Imtiaz