Conditional Validator always returns required

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


['discharge_date', 'required', 'when' => function($model) {

    return $model->discharged == 1;

}],



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?

Show me the code of your action, the models rules and the the code of the view (only the two fields)

The code for in view in _form.php for these two fields are like:


$form->field($model, 'discharged')->checkBox(['label' => 'Discharged', 'uncheck' => '0', 'checked' => '1'])


$form->field($model, 'discharge_date')->widget(DateTimePicker::className(), [

            'language' => 'en',

            'size' => 'ms',

            'template' => '{input}',

            'pickButtonIcon' => 'glyphicon glyphicon-time',

            //'inline' => true,

            'clientOptions' => [

                'startView' => 2,

                'minView' => 0,

                'maxView' => 1,

                'autoclose' => true,

                //'linkFormat' => 'dd-M-yyyy HH:ii P', // if inline = true

                 'format' => 'dd-M-yyyy HH:ii P', // if inline = false

                'todayBtn' => true

            ]

            ])->label('Discharge Date & Time')

I have not altered any code in the controller action, do I need to add some code in the controller for that?

The options "uncheck" and "checked" are not necessary. Remove them and test it.

I don’t think that “uncheck” option exists. And “checked” requires a boolean and indicates if the field should be checked.

So maybe it always check it.

Hi Timmy78 I have updated the code as per ur suggestion, but the behavior is still the same. Even when I don’t select discharged and try to update the form, the required validation for discharge_date is thrown.

Your action is update ? Maybe the value of “discharged” id “1” and the attribute is not safe (can’t modify)

Yes the action is update. But the value of discharged is ‘0’ and yes I have not set the attribute as safe. How I need to modify it.

Note: I have also checked it for create, there also the same behavior.

Thanks.

Show me the rules




public function rules()

    {

       

        return [

            [[ 'admission_date','discharge_date', 'doctor_appointment_date', 'operation_date'], 'safe'],

            [[ 'package','tpa_name',  '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;

            }],

            

                      

        ];

    }



Yes "discharged " is not safe. Add :


['discharged', 'integer']

Ok. But still the same result!

So you have to debug it.

  • In the action, check $_POST

  • In the action, after load(), Check $model->getAttributes();

  • In the "when", check the value

I can’t help you

Hi Timmy

In the action, $_POST

I am getting the values like this:




array (size=2)

  '_csrf' => string 'YWZZTUlOWVYYDxEMfSQeZCI3IDp9Gh0RVQ4WAzkHNTQRAigvGSwcHA==' (length=56)

  'PatientDetail' => 

    array (size=18)

      'ipd_patient_id' => string '10' (length=2)

      'patient_name' => string 'Rajesh Sharma' (length=13)

      'general_regn_no' => string '' (length=0)

      'admission_date' => string '27-Feb-2015 06:45 PM' (length=20)

      'room_category' => string '1' (length=1)

      'tpa_name' => string '' (length=0)

      'advance_amount' => string '' (length=0)

      'discharged' => string '0' (length=1)

      'discharge_date' => string '' (length=0)

      'bed_type' => string '2' (length=1)

      'package' => string '' (length=0)

      'ref_doctor' => string '' (length=0)

      'ref_doctor_other' => string '' (length=0)

      'consultant_doctor' => string '' (length=0)

      'doctor_appointment_date' => string '' (length=0)

      'operation_name' => string '' (length=0)

      'operation_charges' => string '' (length=0)

      'operation_date' => string '' (length=0)

As you can see, the value in the POST is "0" as we want.

After you have to check if the value in the attribute is "0" as we except




$model->load(Yii::$app->request->post());

var_dump($model->discharged);die;



If not, check is the model :




['discharge_date', 'required', 'when' => function($model) {

  var_dump($model->discharged);die;

  return $model->discharged == 1;

}],



Hi Timmy


if ($model->load(Yii::$app->request->post()) && $model->save()) {

            //var_dump($_POST);EXIT;   

            var_dump($model->discharged);exit;

I am getting


string '0' (length=1)

I am not able to dump the when value as before that the required validation is thrown:


['discharge_date', 'required', 'when' => function($model) {

                var_dump($model->discharged);die;

                return $model->discharged ==1;

               

                

            }],

Your validator is right. Unfortunately, after messing with this for hours I found it doesn’t work with check box or radio. Switch it to a dropdownlist and see if it works.


<?= $form->field($model, 'discharged')->dropDownList([0 => 'No', 1 => 'Yes'], ['prompt' => 'Select Discharg Status']) ?>

Here’s my post about it

i also opened a issue on git

Git issue 7496