【问题标题】:I want to make set of fields to be required if another set of fields are empty in yii2. Any one set of fields needs to be fill(required) perfectly如果 yii2 中另一组字段为空,我想设置一组字段。任何一组字段都需要完美填写(必填)
【发布时间】:2020-08-22 23:08:21
【问题描述】:

我正在制作录取表格,我需要获取家长信息。因此,有一个条件是任何一个父母的数据都需要完美填充。意味着如果我不填写父亲的详细信息,那么母亲的所有字段都将是必需的。如果我填写父亲的任何信息字段,那么在父亲的详细信息中,所有字段都需要填写,反之亦然。

这是我的 AdmissionForm 模型代码:

public function rules()
{
    return [
      [['firstname', 'middle_name', 'surname_name'],'required'],
      [['residential_telephone_no',],'required'],
      [['father_name', 'father_qualification', 'father_occupation', 'father_mobile_no', ], 'safe'],//this needs to be alternately required 
      [['mother_name', 'mother_qualification', 'mother_occupation', 'mother_mobile_no', ], 'safe'],//this needs to be alternately required
      [[ 'admission_date'], 'safe'],
      [['form_id'], 'required'],
      [['aadhaar_no'], 'match', 'pattern' => '/^\d{12}$/', 'message' => 'Field must contain exactly 12 digits.',],
    ];
}

我只想捕捉任何一位父母的详细信息。

【问题讨论】:

    标签: validation yii2 conditional-statements alternate


    【解决方案1】:

    您可以使用yii\validatprs\Validator::$when 回调来指定是否应该应用规则。如果应该使用该规则,回调应该返回 true。

    例如,当母亲姓名为空时,我们可以将父亲的详细信息设为必填字段:

    [
        ['father_name', 'father_qualification', 'father_occupation', 'father_mobile_no'],
        'required',
        'when' => function ($model) {
             return empty($model->mother_name);
        }
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-02
      • 2021-05-29
      相关资源
      最近更新 更多