如果表单属性值为空,则使用 Yii 规则验证更改属性名称

Use Yii rule validation to change attribute name if form attribute value is empty

我有一个扩展 Yii CFormModel 的模型,我想定义一个 验证规则 检查属性值是否为空并且 - 如果是这种情况 - 将 属性名称 设置为空字符串而不是更改输入值。

这种情况是否可能,或者验证规则是否仅用于警告 and/or 输入值的更改?

如有任何帮助,我们将不胜感激。

下面是我的模型的示例代码:

class LoginForm extends CFormModel
{
    public $firstName;
    public $lastName;

    public function rules()
    {
        return array(
            array('firstName, lastName', 'checkIfEmpty', 'changeAttributeName'),
        );
    }
    // some functions
}

不确定您的用例是否非常优雅,但以下应该可行:

class LoginForm extends CFormModel
{
    public $firstName;
    public $lastName;

    public function rules()
    {
        return array(
            array('firstName, lastName', 'checkIfEmpty'),
        );
    }

    public function checkIfEmpty($attribute, $params) 
    {
        if(empty($this->$attribute)) {
            unset($this->$attribute);
        }
    }

    // some functions
}

根据 hamed 的回复,另一种方法是使用 beforeValidate() 函数:

class LoginForm extends CFormModel
{
    public $firstName;
    public $lastName;

    protected function beforeValidate()
    {
        if(parent::beforeValidate()) {
            foreach(array('firstName, lastName') as $attribute) {
                if(empty($this->$attribute)) {
                    unset($this->$attribute);
                }
            }
        }
    }

}

CModel 有 beforeValidate() 方法。此方法在 yii 自动模型验证之前调用 您应该在您的 LoginForm 模型中覆盖它:

protected function beforeValidate()
    {
        if(parent::beforeValidate())
        {

            if($this->firstname == null)
               $this->firstname = "Some String";
            return true;
        }
        else
            return false;
    }

您可以使用默认规则集。

public function rules()
{
        return array(
           array('firstName', 'default', 'value'=>Yii::app()->getUser()->getName()),
        );
}

请注意,这将 运行 在验证时进行,这通常是在提交表单之后。它不会使用默认值填充表单值。您可以使用 afterFind() 方法来做到这一点。