Dmitry Petrik
Dmitry Petrik

Reputation: 113

Yii2 Get current action in controller

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

Upvotes: 11

Views: 33152

Answers (4)

Imtiaz
Imtiaz

Reputation: 2524

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

Upvotes: 6

he11d0g
he11d0g

Reputation: 311

if use Yii2 in view - try this: $this->context->action->id;

Upvotes: 14

Kalpesh Desai
Kalpesh Desai

Reputation: 1421

You can get current action id by :)

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

Upvotes: 3

arogachev
arogachev

Reputation: 33538

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;
    }
}

Upvotes: 16

Related Questions