Yii 1: UrlManager does not call correct action in module controller

I am creating a module API

in an application and I need to set some rules in urlManager

, however, when I set one rule and check it, if it works, it calls the index action instead of the desired action.

in the controller

<?php     
Class ProjectsController extends Controller
{
    // Do nothing on this request
    public function actionIndex()
    {
        // this is being echoed even if this action is not being requested
        echo 'test';
    }

    /*
    *   Retrieve all projects
    */
    public function actionAll()
    {
        $projects = Project::model()->findAllApi();

        echo CJSON::encode($projects);
    }

    public function actionView($id)
    {
        echo 'asd';
    }
}

      

urlManager in config / main.php

'urlManager'=>array(
            'urlFormat'=>'path',
            'showScriptName'=>false,
            'urlSuffix'=>'.php',
            'rules'=>array(
                '<module:\w+>/<controller:\w+>/<id:\d+>'=>'<module>/<controller>/view',
                '<controller:\w+>/<id:\d+>'=>'<controller>/view',
                '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
                '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
            ),
        ),

      

ApiModule.php

<?php

class ApiModule extends CWebModule
{
    public function init()
    {
        // this method is called when the module is being created
        // you may place code here to customize the module or the application

        // import the module-level models and components
        $this->setImport(array(
            'api.models.*',
            'api.components.*',
        ));
    }

    public function beforeControllerAction($controller, $action)
    {
        if(parent::beforeControllerAction($controller, $action))
        {
            // this method is called before any module controller action is performed
            // you may place customized code here
            return true;
        }
        else
            return false;
    }
}

      

so if i query http://localhost/<application>/api/projects/2

it calls the index action instead of the view. How to fix it?

+3


source to share


1 answer


Everything is correct in your code. I have not found any errors in your code! However, try to remove the rule '<module:\w+>/<controller:\w+>/<id:\d+>'=>'<module>/<controller>/view'

and replace api/projects/<id:\d+>

=> api/projects/view

. This might be helpful.



+1


source







All Articles