G
G
Ghost26922018-04-30 19:01:01
Yii
Ghost2692, 2018-04-30 19:01:01

How to display validation error for form field in Yii2?

How to display validation error for old_password form in Yii2?
$this->addError() doesn't work.

public static function tableName()
    {
        return 'user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['first_name', 'last_name', 'email', 'repeat_password', 'old_password', 'new_password'], 'required'],
            [['is_admin'], 'integer'],
            [['created'], 'safe'],
            [['first_name', 'last_name', 'email', 'auth_key', 'token'], 'string', 'max' => 191],
            [['repeat_password', 'old_password', 'new_password'], 'string', 'max' => 191],
            ['old_password', 'validatePassword'],
            ['repeat_password', 'compare', 'compareAttribute' => 'new_password'],
        ];
    }

    /**
     * @inheritdoc
     */

    public function validatePassword()
    {
        if (!$this->hasErrors()) {
            $u = User::find()->where(['id' => Yii::$app->user->id])->one();
            $user = $u->password;

            if (Yii::$app->getSecurity()->validatePassword($this->old_password, $user)) {
                var_dump('success');
            }else{
                $this->addError('old_password', 'Incorrect username or password.');
//                var_dump('error');
            }
        }
    }

and controller
$model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $model->password = \Yii::$app->getSecurity()->generatePasswordHash($model->repeat_password);
            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        }

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
A
Andrey, 2018-04-30
@reaferon

In the model

['old_password', 'validatePassword','message' => 'Какая-то ошибка'],

D
Dmitry Kim, 2018-04-30
@kimono

The thing is, you don't have a client-side implementation of validatePasword. Therefore, the error will be displayed only after the form is loaded and the page is reloaded. I think the clientValidateAttribute method in validators can help.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question