How Can I Get The Controller, Action And Parameter Of The Current Request Inside A View

TL;DR…read the title.

If you have the patient, read the following.

I have a multilingual website that allow admin to add and remove language whenever he wanted.

I have the following routes:

‘<language>/medias’=>‘site/medias’,

‘<language>/about/<slug>’=>‘site/about’,

I have extended CUrlManager:




class UrlManager extends CUrlManager

{

	public function createUrl($route,$params=array(),$ampersand='&')

	{

		if ( !isset($params['language']) ) {

			if ( Yii::app()->user->hasState('language') )

				$language = Yii::app()->user->getState('language');

			else

				$language = Language::main(); // get default language from the database

		} else {

			if ( Language::useful($params['language']) )

				$language = $params['language'];

			else

				$language = Language::main(); // get default language from the database

		}


		$params['language'] = $language;


		return parent::createUrl($route, $params, $ampersand);

	}

}



…so that when I type this:


$this->createUrl('site/about', array('slug'=>'our-team'));

it will automatically append a language code and generate this:


/en/about/our-team

The problem is when I tried to implement a language switcher.

For example, when you are at this url: /en/about/our-team, if you click the language switcher, I want to redirect user to /fr/about/our-team

For now, I use this method:


$baseUrl . '/' . $avaliable_language['code'] . strstr(Yii::app()->request->pathInfo, '/')

It works fine but I was thinking is there a more elegant way to do this using the createUrl method. So what I couldn’t figure out right now is how can I get the current controller, action and parameter (i.e slug) inside a view.

In view layer

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

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

or

In view file -

$this->uniqueid controller name,

$this->action->Id action name. ($this is CController instance)

Thanks. How about the parameter of the current request?

Hi,

i missed :(

$id = Yii::app()->getRequest()->getQuery(‘id’);

or

$id = Yii::app()->request->getParam(‘id’);

:) cheers

If I’m not wrong, by using path format, parameters are parsed instead or passed by GET, so $_GET is useless. I guess my real question is how do I get ALL the parameters instead of accessing it one by one, since I have a lot of route with varying number of parameters.

When routes are parsed $_GET is populated based on your url rules. Already existing params from $_GET will be still there, so having a route like




'controller/action/<name:([a-zA-Z]+)' => 'controller/action'



and accessing it like




somecontroller/someaction/abcdef?param1=1&param2=2



will give you a $_GET of




array( 'name' => 'abcdef', 'param1' => 1, 'param2' => 2 )