Yii2:条件验证器始终返回必需的值


Yii2: Conditional Validator always returns required

我正在尝试使用Yii2的条件验证器,如指南中所示:

型号代码

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;
        }],

    ];
}

在我的控制器中,比如:

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,
            ]);
        }
    }

但是,无论我是否选择作为复选框字段的出院字段,出院日期都会根据需要返回。

我在这里做错了什么?

似乎默认情况下Yii2将在服务器端和客户端进行验证。查看Yii2文档Conditional Validation部分中的示例:

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

您还需要一个'whenClient'代码,或者正如@Alexandr Bordun所说,通过'enableClientValidation' => false禁用客户端验证。

尝试添加enableClientValidation参数如下:

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

这只在使用模型名称(客户端验证)时对我有效。

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

['package_id_fk', 'required', 'when' => function($model) {return $model->type == 'PACKAGE';}, 'enableClientValidation' => false],

它对我有效。

我有类似的需求,我使用以下代码解决了它

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