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

11,340
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()

Share:
11,340
Yasin Patel
Author by

Yasin Patel

Web Developer ( Yii2 and Laravel )

Updated on June 16, 2022

Comments

  • Yasin Patel
    Yasin Patel almost 2 years

    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.