有条件地要求模型属性 - 如何?

时间:2014-07-21 08:47:03

标签: php validation yii yii2

我有一个模型User,其中包含typepayment_id属性。

payment_id type == 1时需要

type == 3,如果type == 2

,则可能为空

在我的表单中,type是包含值1 23的下拉列表。 payment_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

有人可以指出我的错误吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

变化:

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

要:

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

答案 1 :(得分:0)

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

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为客户端验证添加相同的条件。