从模型中的函数向视图添加错误

时间:2014-09-22 14:10:57

标签: php yii

我正在编写用户更改Yii框架内密码的功能。视图要求用户输入他当前的密码和他的新密码两次。为了比较旧密码,我在模型中添加了以下方法

public function findPassword(){
        $user = Users::model()->findByPk(Yii::app()->user->id);
        if(password_verify($user->password,$this->oldPassword) !== true){
            $this->addError($this->attribute,'Old password is incorrect');
        }
    }

我在模型中有以下规则。

array('old_password', 'findPassword', 'on' => 'changePwd'),

当我执行此操作并转到表单并尝试更改密码时,我会收到以下error

1 个答案:

答案 0 :(得分:1)

试试这个:

public function findPassword(){
    $user = Users::model()->findByPk(Yii::app()->user->id);
    if(password_verify($user->password,$this->oldPassword) !== true){
        $this->addError('old_password','Old password is incorrect');
    }
}

示例:http://www.yiiframework.com/wiki/168/create-your-own-validation-rule/