Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2: Conditional Validator always returns required

I am trying to use Yii2's conditional validator as given in the guide like:

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 like:

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 whether I select or not the discharged field which is a checkbox field, the discharge date alwasys returns as required.

What I am doing wrong here?

like image 794
Pawan Avatar asked Feb 27 '15 02:02

Pawan


2 Answers

It seems that by default Yii2 will do validation in BOTH Server side and Client side. Check the example in Conditional Validation part of Yii2 doc:

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

you also need a 'whenClient' code, or as @Alexandr Bordun said, to disable the client validation by 'enableClientValidation' => false.

like image 142
Andy Ding Avatar answered Nov 07 '22 16:11

Andy Ding


Try to add enableClientValidation parameter as the following:

 ['discharge_date', 'required', 'when' => function($model) {
        return $model->discharged == 1;
 }, 'enableClientValidation' => false]
like image 14
Alexandr Bordun Avatar answered Nov 07 '22 16:11

Alexandr Bordun