A regular web controller (not REST ).

 if ($model->hasErrors()) { Yii::$app->getResponse()->setStatusCode(400); } 

In the body of action for some reason does not work. Example:

 public function actionSave($model, $AJAXvalidate = false) { $post = Yii::$app->request->post(); if ($model->load($post) && $model->save()) { Yii::$app->session->addFlash('success', 'Запись успешно сохранена.'); return $this->redirect(['index']); } else { if (!Yii::$app->request->isPost) { $model->loadDefaultValues(); } if ($model->hasErrors()) { Yii::$app->getResponse()->setStatusCode(400); } return $this->render('form', [ 'model' => $model, ]); } } 

PS As it turned out, does not work in action games if they are determined through the treit. If you define an action right in the controller, then the code works. Why is that?

  • Does it reach the method? Tried debazhit? - Urmuz Tagizade
  • Yes, it comes. $model->hasErrors() == true - Mik
  • Yii :: $ app-> response-> statusCode = 400; It seems to be more correct ... - Urmuz Tagizade
  • It does not work either. - Mik
  • one
    In most cases, the default value of yii \ web \ Response :: statusCode is 200. If the above didn’t work, throw the corresponding HTTP exception: throw new \ yii \ web \ BadRequestHttpException; - Urmuz Tagizade

1 answer 1

The reason is more than trivial: the Pjax widget sets the status to 200 when called. And since it is called in the view when rendering, the status set in the controller action is interrupted.