We know that ActiveForm validates the form inputs on the Client-side as well as on the server-side. We get Client-side validation errors immediately but we need to handle the server side errors a bit differently. Let’s see how we can do that.
First, in the controller action when you are about to load the $model
, just add this line $model->validate()
as shown below.
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
//$model is loaded with the form data and it has passed all the validation rules
}
else{
// validation failed
// to get the errors
$errors = $model->getErrors();
//then we can pass the $errors to the view or trigger setFlash from here with error message(s).
}
Alternatively, we can use Html::errorSummary()
to display errors on the view.
//view file
use yii\helpers\Html;
if($errors){
Html::errorSummary($model);
}
It handles the displaying of the errors for you. The errors will be displayed right next to the Input field which has error just like the Yii Client-side validations.