Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use both beforeAction() and behaviors() method in controller in Yii2

I want to use both beforeAction() and behaviors() method in my controller.

If i add beforeAction() method in my code than behaviors() method is not working.

And if i remove beforeAction() method than behaviors() method is working.

I dont want to remove beforeAction() as it is use to disable csrf token for ajax calls.

public function beforeAction($action)
{
  if($action->id =='ignore' || $action->id =='accept')
  {
    $this->enableCsrfValidation = false;
  }
  return true;
}

And i want to use behaviors() method for authentication.

public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::className(),
            'only' => ['create','index','update','change','view','page','active','list'],
            'rules' => [
                [
                    'actions' => ['create','index','update','change','view','page','active','list'],
                    'allow' => true,
                    'roles' => ['@'],
                    'matchCallback' => function ($rule, $action)
                    {
                      echo "string";
                      die;
                    },
                ],
            ],
            'denyCallback' => function ($rule, $action) {
                return $this->redirect(Yii::$app->request->baseUrl);
            }
        ],
    ];
}

Is there any way to use both method in same controller.

like image 996
Yasin Patel Avatar asked Dec 06 '22 14:12

Yasin Patel


1 Answers

public function beforeAction($action)
{
  if($action->id =='ignore' || $action->id =='accept')
  {
    $this->enableCsrfValidation = false;
  }
  //return true;
  return parent::beforeAction($action);
}

you need to return the parent beforeAction()

like image 90
Kandarp Patel Avatar answered Jan 09 '23 14:01

Kandarp Patel