Dean
Dean

Reputation: 425

Create controller in Yii Framework

i create new controller in yii look like this:

class LanguageController extends Controller
{

    public function actionSwitchLanguage($language)
    {
        Yii::app()->session = $language;
        $this->redirect(Yii::app()->request->urlReferrer);
    }
}

in views file, i create new url look like this:

<a href="<?php echo Yii::app()->controller->createUrl('Language/actionSwitchLanguage',array('language'=>'en')); ?>">English</a>

but when clicking the link, it appears error:

Error 404
The system is unable to find the requested action "actionswitchlanguage".

somebody can help me?

Upvotes: 2

Views: 3935

Answers (3)

Arya
Arya

Reputation: 504

Try this,

<a href="<?php echo Yii::app()->controller->createUrl('Language/switchLanguage',array('language'=>'en')); ?>">English</a>

Upvotes: 1

Let me see
Let me see

Reputation: 5094

If you are creating Url like this, I mean using controller

Yii::app()->controller->createUrl('switchLanguage',array('language'=>'en')); 

then you do not need to tell the createUrl about the controller name. just pass the action Name without the action keyword as kumar_v has said.


The above statement is similar to

$this->createUrl('switchLanguage',array('language'=>'en')); here the $this is the object of the current controller, so here also you do not need to tell createUrl() about the controller name

Note:- The view should be of the same controller.

But if you are creating urls like

Yii::app()->createUrl('language/switchLanguage',array('language'=>'en'));

then you need to tell the createUrl() method about the controller as well as action (but without action Keyword :) )

Update

In your config/main.php

Uncomment the following portion

'urlManager'=>array(
            'urlFormat'=>'path',
            'rules'=>array(
                '<controller:\w+>/<id:\d+>'=>'<controller>/view',
                '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
                '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
            ),
        ),

Upvotes: 0

Kumar V
Kumar V

Reputation: 8838

try this code:

No need to add action in while creating url.

No need to mention controller name as you are creating url from controller object.

<a href="<?php echo Yii::app()->controller->createUrl('switchLanguage',array('language'=>'en')); ?>">English</a>

Upvotes: 0

Related Questions