1
votes

I have created a module in Yii2 using Gii code generator. My new generated module location is

backend/modules/cms

cms is new generated module name.

backend/config/main.php after setting module configuration looks as following

return [

    'id' => 'app-backend',
    'basePath' => dirname(__DIR__),
    'controllerNamespace' => 'backend\controllers',
    'bootstrap' => ['log'],
    'modules' => [
        'gii' => [
            'class' => 'yii\gii\Module', //adding gii module
            'allowedIPs' => ['127.0.0.1', '::1']  //allowing ip's 
        ],
        'cms' => [
            'class' => 'backend\modules\cms\Cms',
    ],
    ],
    'components' => [
        'user' => [
            'identityClass' => 'common\models\User',
            'enableAutoLogin' => true,
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
            ],
        ],
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        'urlManager' => [
            'class' => 'yii\web\UrlManager',
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
                '<controller:\w+>/<action:\w+>/<id:\w+>' => '<controller>/<action>',
                '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
                                
                '<module:\w+>/<controller:\w+>/<action:\w+>' => '<module>/<controller>/<action>',
                '<module:\w+><controller:\w+>/<action:update|delete>/<id:\d+>' => '<module>/<controller>/<action>',
            ]
        ],
        'assetManager' => [
            'bundles' => [
                'yii\web\JqueryAsset' => [
                    'js' => []
            ],
        ],
    ],
    ],
    'params' => $params,
];

behaviors function in controller looks as after setting access rules

public function behaviors() {
        return [
	'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index', 'create', 'update', 'delete'],
                        'allow' => true,
                        'roles' => ['@'],
                ],
            ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                'delete' => ['post'],
            ],
                ],
        ];
    }

Only index action of my controller is accessible. when i access any other action in controller url changes but shows index action contents.

How can i access all actions in controller?

It will be appreciable if someone help me resolving this issue. my controller

namespace backend\modules\cms\controllers;

use Yii;
use yii\filters\AccessControl;
use backend\modules\cms\models\Pages;
use backend\modules\cms\models\PagesSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * PagesController implements the CRUD actions for Pages model.
 */
class PagesController extends Controller
{
   public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                    'actions' => ['logout', 'index', 'create', 'update', 'delete'],
                    'allow' => true,
                    'roles' => ['@'],                        
            ],
            ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
//                'delete' => ['post'],
            ],
                ],
        ];
    }

    /**
     * Lists all Pages models.
     * @return mixed
     */
    public function actionIndex()
    {

        $searchModel = new PagesSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->post());

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Pages model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Pages model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        echo "here";
        exit;
        $model = new Pages();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index']);
        } else {

            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Pages model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Pages model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Pages model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Pages the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Pages::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not    exist.');
        }
    }
}

I am using Url as follows: http://localhost/yii2-demo/backend/cms/pages/index

http://localhost/yii2-demo/backend/cms/pages/create

2
Can you post your controller code? - brunoapimentel
updated post with my controller - Sohail Bhutta

2 Answers

0
votes

What Url(s) are you using? For a module it should be: ?r=cms/pages/index, ?r=cms/pages/create etc...

0
votes

The only problem I can spot is on your $matchCallback attribute on the second AccessControl rule. It should use this signature

function ($rule, $action)

And it should return a boolean that indicates wheter this rule should be applied or not. In your case, you're saying that it should be applied to users that are not guests and that have the role '0'. You're also calling a redirect inside the function, and it doesn't return a boolean. See more info here http://www.yiiframework.com/doc-2.0/yii-filters-accessrule.html#$matchCallback-detail

Try to remove this attribute completely and see if you get a different result.