YII场景:怎么样?

时间:2013-09-25 11:24:30

标签: php yii yii-cmodel

如果我有一个输入字段,例如:

  • USEREMAIL:
  • UserPhoneNumber:
  • UserOldPasword:
  • UserNewPassword:
  • UserRetypePassword:

在我的操作更新中,如果UserOldPassword不为空,我将只需要UserNewPassword,否则唯一需要更新的是UserEmail或UserPhoneNumber。我将如何实施此规则?仅在更新时?或者我应该在我的模型上创建自定义验证器吗?

所以在我的afterFind()上我有这段代码来避免输出哈希密码:

public function afterFind()
{
    //reset the password to null because we don't want the hash to be shown.
    $this->old_password = $this->password;
    $this->password = null;

    parent::afterFind();
}

我创建了一个自定义验证。它确实有问题,问题是即使我提交了空的UserNewPassword表单我仍然收到错误,$ this->密码字段现在从我的数据库返回一个散列值

请查看我的代码并更正我的错误:

public function checkForEmpty($attribute,$params){
        if(!empty($this->$attribute)){
            if(empty($params['oldPassword'])){
                $this->addError('oldPassword','We require your old password to proceed changing password');
            }
            if(empty($params['retypePassword'])){
                $this->addError('retype_password','To assure that you type the right password please retype your password');
            }
            if(!empty($params['oldPassword']) && !empty($params['retypePassword'])){
                $this->compareOldPass($params['oldPassword'],$this->old_password);
            }
        }

    }

提前致谢...

1 个答案:

答案 0 :(得分:1)

你可以在你的模型中做一个beforeSave()。我认为这是最好的解决方案,因为您的逻辑复杂,并且不是您的应用程序的全局问题。

更新:

public function beforeSave()
{
    if(parent::beforeSave())
    {
        //implement you logic here

        //or check it is a new record
        if($this->isNewRecord)
        { 
            // do stuff here if new 
        }

        //or you can return false if it doesn't meet your logic


        return true;
    }
    else
        return false;
}