Get current controller and action id in Yii

85,353

Solution 1

Yes you can get the current controller/action route, by reversing urlManager rule:

Yii::app()->urlManager->parseUrl(Yii::app()->request)

Solution 2

Did you try:

Yii::app()->controller->id

and:

Yii::app()->controller->action->id

?

Solution 3

As now in Yii2

get current controller name

Yii::$app->controller->id

current controller object

Yii::$app->controller

current action name:

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

current route:

Yii::$app->requestedRoute

Solution 4

Using Yii2, obtain the current controller object with:

Yii::$app->controller

From the controller, obtain the current action as a string using:

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

Solution 5

In Yii2:

The problem of calling Yii::$app->controller->id is that when you call it somewhere (example: in one of your top-level abstract controller), Yii::$app->controller might not be instantiated yet, so it will return error.

Just directly call urlManager to map request to route:

var_dump(Yii::$app->urlManager->parseRequest(Yii::$app->request))
Share:
85,353
Hamid Ghorashi
Author by

Hamid Ghorashi

Updated on July 01, 2020

Comments

  • Hamid Ghorashi
    Hamid Ghorashi almost 4 years

    I want to force all users to log in before accessing pages of my site. I have followed Larry Ullman's tutorial Forcing Login for All Pages in Yii.

    According to the tutorial you can make an exception for some pages to avoid redirecting to the log in page. In order to check the current controller it has checked $_GET value. My problem is that I have used urlManager to rewrite the URL and $_GET gives me a null value. Is there any method I can use to get the current controller and action in the score of my class?

    I tried the following but it is not accessible in the scope of my component class:

    Yii::app()->controller->getId