Get current controller and action id in Yii
Asked Answered
I

8

32

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
Inadvertent answered 15/10, 2013 at 8:53 Comment(1)
For Yii2 it is similar: Yii::$app->controller->id, Yii::$app->controller->action->idGrethel
A
49

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

Yii::app()->urlManager->parseUrl(Yii::app()->request)
Ardeb answered 15/10, 2013 at 9:26 Comment(2)
Just a note, this doesn't work when the index page is loaded, i.e http://localhost/yiiapp/ as there is no request in the URL. @korcholis's is the best way to make it work for all actions, whether index or not.Keating
Simple and fast : Yii::$app->requestedRouteSpacecraft
B
51

Did you try:

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

and:

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

?

Barraza answered 15/10, 2013 at 8:58 Comment(4)
It doesn't work. Yii::app()->controller returns nullInadvertent
try Yii::$app->controller->idCeria
@Ceria It will work only in Yii2! In Yii1 app is a method, not a variable of Yii class. The only working way is calling Yii::app() in Yii1.Self
For Yii 2, use Yii::$app->controller->idWalkout
A
49

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

Yii::app()->urlManager->parseUrl(Yii::app()->request)
Ardeb answered 15/10, 2013 at 9:26 Comment(2)
Just a note, this doesn't work when the index page is loaded, i.e http://localhost/yiiapp/ as there is no request in the URL. @korcholis's is the best way to make it work for all actions, whether index or not.Keating
Simple and fast : Yii::$app->requestedRouteSpacecraft
L
22

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
Loyal answered 25/3, 2015 at 9:27 Comment(2)
BTW, Yii::$app->request->resolve()[0] for getting route before request event, while others could not be get at that time.Bevbevan
This is what I was looking for @NickTsai. Thank you.Ferrell
F
12

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
Fullblooded answered 24/10, 2014 at 16:20 Comment(0)
H
8

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))
Hyperthyroidism answered 20/11, 2015 at 18:9 Comment(1)
Yes, this works also in module context, eg: admin/permission/indexDalia
C
5

Try Yii::app()->controller->getRoute()

Cabalist answered 15/10, 2013 at 9:2 Comment(2)
I get this error: Call to a member function getRoute() on a non-objectInadvertent
In Yii2: Yii::$app->controller->getRoute()Murphree
S
4

If I get you question correctly, you are basically trying to stop access to certain actions in the controller from being accessed without being logged in right?

If this is what you are after, the correct method to do it is this :

  1. Make a actionMethod() in the controller like so :

    class SomeController extends CController{
    
      public function actionSomeAction(){
    
        ... More code...
    
    }
    
  2. After that, you can access the site using : path/to/application/controllerName/actionName

  3. Now if you want to force the user to log in before accessing the action, do this :

Make an access control like so :

 /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

/**
 * Specifies the access control rules.
 * This method is used by the 'accessControl' filter.
 * @return array access control rules
 */
public function accessRules()
{
    return array(

        array('allow', // allow authenticated user to perform 'create' and 'update' actions
            'actions' => array('**yourActionMethodName**'),
            'users' => array('@'),
        ),

        array('deny', // deny all users
            'users' => array('*'),
        ),
    );
}

Now only authenticated users would be able to access the URL.

I hope it solved your problem.

If you simply want to check if the user is a guest and if he is, send him to the login page everytime:

In the config/main.php, add the following :

'defaultController' => 'controllerName/actionMethod',

And in that controller just add the above access rule. Now, by default you are opening the site to an access controlled method. So it would automatically redirect you to the login page.

Even another method :

Just add this in the views/layouts/main.php

<?php 

if(Yii::app()->user->isGuest)
{ 
   $this->redirect('/site/login');
}
?>
Sanitation answered 15/10, 2013 at 9:11 Comment(3)
Thank you so much, but the I don't want to write access rules for every controller. I just want to make a check if the user is guest and then redirect it to the login page. But other than the scenario I explained above, I am trying to find find out how to get access to the controller and action ID while using urlManager to rewrite the URL.Inadvertent
I have edited my post. Maybe it should help you now. If it does, please dont forget to upvote and rate it as the answer :)Sanitation
Thank you very much. I got my answer.Inadvertent
N
0
if (Yii::$app->requestedAction->id == "index") {
    //do something
}
Nansen answered 25/1, 2016 at 10:51 Comment(1)
Please refrain from answering with just code and explain how your answer differs from the (long) existing other answers.Clarisclarisa

© 2022 - 2024 — McMap. All rights reserved.