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


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

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

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

任何帮助都将不胜感激。

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

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自动模型验证之前调用您应该在您的登录表单模型中覆盖它:

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()方法来完成此操作。