Yii2: The conditional validator always returns the required

I am trying to use the Yii2 conditional validator as indicated in the manual, for example:

Model code

public function rules() { // $discharged = function($model) { return $this->discharged == 1; }; return [ [[ 'admission_date','discharge_date', 'doctor_appointment_date', 'operation_date'], 'safe'], [[ 'package','tpa_name', 'discharged', 'bed_type', 'room_category', 'ref_doctor', 'consultant_doctor', 'operation_name'], 'integer'], [['advance_amount', 'operation_charges'], 'number'], [['patient_name', 'ref_doctor_other'], 'string', 'max' => 50], [['general_regn_no', 'ipd_patient_id'], 'string', 'max' => 20], [['admission_date', 'discharge_date', 'doctor_appointment_date', 'operation_date'],'default','value'=>null], ['ipd_patient_id', 'unique'], [['bed_type','admission_date','room_category'],'required'], ['discharge_date', 'required', 'when' => function($model) { return $model->discharged == 1; }], ]; } 

and in my controller:

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

But regardless of whether I selected or did not upload the field, which is the check box, alwasys release dates are returned as needed.

What am I doing wrong here?

+6
source share
5 answers

It appears that, by default, Yii2 will perform validation on the BOTH server side and client side. Check out the example in the Conditional Validation part of the Yii2 doc :

 ['state', 'required', 'when' => function ($model) { return $model->country == 'USA'; }, 'whenClient' => "function (attribute, value) { return $('#country').val() == 'USA'; }"], 

you will also need the code 'whenClient' or, as @Alexandr Bordun said, to disable client checking for 'enableClientValidation' => false .

+22
source

Try adding the enableClientValidation parameter as follows:

  ['discharge_date', 'required', 'when' => function($model) { return $model->discharged == 1; }, 'enableClientValidation' => false] 
+9
source

This only works for me when using the model name (client validation).

 ['state', 'required', 'when' => function ($model) { return $model->country == 'USA'; }, 'whenClient' => "function (attribute, value) { return $('#MODELNAMEHERE-country').val() == 'USA'; }"] 
+2
source

i had a similar requirement, I solved it using the following code

 ['discharge_date', 'required', 'whenClient' => function($model) { return $model->discharged == 1; }, 'enableClientValidation' => false] 
+1
source
 ['package_id_fk', 'required', 'when' => function($model) {return $model->type == 'PACKAGE';}, 'enableClientValidation' => false], 

This works for me.

+1
source

Source: https://habr.com/ru/post/983078/


All Articles