【问题标题】:Use Yii rule validation to change attribute name if form attribute value is empty如果表单属性值为空,使用 Yii 规则验证更改属性名称
【发布时间】:2015-03-07 19:44:06
【问题描述】:

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

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

任何帮助将不胜感激。

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

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

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

【问题讨论】:

  • 你想用这个实现什么?您只是想忽略所有空属性吗?
  • 是的,我想防止 URL 中出现空属性。

标签: php yii yii-cformmodel


【解决方案1】:

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

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);
                }
            }
        }
    }

}

【讨论】:

    【解决方案2】:

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

    protected function beforeValidate()
        {
            if(parent::beforeValidate())
            {
    
                if($this->firstname == null)
                   $this->firstname = "Some String";
                return true;
            }
            else
                return false;
        }
    

    【讨论】:

    • @atreju:你试过我的解决方案了吗?
    • 是的,我刚刚做了,谢谢。我认为我的问题有点含糊不清——我需要取消设置属性而不是给它一个默认值,以使其从 URL 中“消失”。但是你的方法结合 vim 应该可以工作!
    【解决方案3】:

    您可以使用默认规则集。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      相关资源
      最近更新 更多