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

1.5k views Asked by At

i am creating an API module in an application and i have to set some rules in urlManager, however when i set a single rule and test it if it's working, it calls the index action instead of the desired action.

in 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 request http://localhost/<application>/api/projects/2 it calls index action instead of view. how to fix this?

1

There are 1 answers

3
hamed On BEST ANSWER

Everything is correct in your code. I didn't find any error in your code! However try to remove '<module:\w+>/<controller:\w+>/<id:\d+>'=>'<module>/<controller>/view' rule and replace api/projects/<id:\d+> => api/projects/view. This could be helpful.