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


Adding an error to the view from a function in the model

我正在为用户在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'),

当我这样做并在表单上尝试更改密码时,我会收到以下错误

试试这个:

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/