【问题标题】:model attribute conditionally required - how?有条件地需要模型属性 - 如何?
【发布时间】:2014-07-21 08:47:02
【问题描述】:

我有一个模型User,它具有typepayment_id 属性。

type == 1 时需要payment_id type == 3,但type == 2 时可能为空

在我的表单中,type 是一个下拉列表,包含值 1 23payment_id 是一个常规文本字段。选择值 2 时,仍会提示我输入 payment_id

我根据yii2 docs尝试过的代码:

class User
{    
    public function rules()
    {
        return [
            [['payment_id', 'type'], 'integer'],
            [
                ['payment_id'], 'required', 'when'=>function ($model) {
                    return ($model->type == 1 || $model->type == 3);
                }
            ],
            ...
        ];
    }
    ...
}

但即使type == 2(在下拉列表中),我仍然收到错误Payment ID may not be empty

谁能指出我的错误?

谢谢!

【问题讨论】:

    标签: php validation yii yii2


    【解决方案1】:

    变化:

    return ($model->type == 1 || $model->type == 3);
    

    收件人:

    return ($model->$type !== 2 ? ($model->type == 1 || $model->type == 3) : $model->type == NULL);
    

    【讨论】:

    • 感谢您的回答,但似乎不起作用;我仍然收到错误Payment ID may not be empty
    【解决方案2】:

    好的,我找到了解决方案,这是工作代码:

    public function rules()
    {
        return [
            [
                ['payment_id'], 'required', 'when' => function ($model) {
                    return ($model->type == 1 || $model->type == 3);
                }, 'whenClient' => "function (attribute, value) {
                    return ($('#user-type').value == 1 || $('#user-type').value == 3);
                }"
            ],
        ];
    }
    

    解释:我的表单首先在客户端进行验证,阻止我发布表单。所以我需要使用whenClient 在客户端验证中添加相同的条件。

    【讨论】:

      猜你喜欢
      • 2016-12-07
      • 1970-01-01
      • 1970-01-01
      • 2021-07-15
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多