A
A
Andrey Klyuev2014-05-04 21:26:42
Yii
Andrey Klyuev, 2014-05-04 21:26:42

How to setup Rules() for model in Yii2

There is a UserForm model (it comes out of the box like the SignupForm in the frontend) for the add user/user registration form. I want to use the same model to edit the user and change the personal data of the user.
How to properly set up rules() so that when validating unique fields, the user being changed is not checked.
The default is:
public function rules()
{
return [
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['username', 'unique' , 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'unique', 'targetClass ' => '\common\models\User', 'message' => 'This email address has already been taken.'],
['password', 'required'],
['password', 'string', 'min ' => 6],
];
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya Pushtov, 2015-03-05
@BBird

For the author, most likely, the question is no longer relevant, but it may be useful to someone.
Faced the same problem. I solved it as follows, using the default validator:
1. copy the $model->username field to $model->oldUsername.
2. in rules we write the following:

public function rules() {
    return [
        //...
        ['username', 'unique', 'targetClass' => Users::className(), 'message' => 'Имя пользователя уже занято', 'filter' => ['!=', 'username', $this->oldUsername]],
        //...
    ];
}

Actually, here is the documentation page that helped solve the problem: www.yiiframework.com/doc-2.0/yii-validators-unique...

S
Sergey, 2014-05-04
Protko @Fesor

Feel free to read the documentation, specifically the part about scripts.
In short, in Yii, two validation scenarios are set by default for models - insert (when inserting) and update (when updating an existing record). Your validation rule just needs to be set for the insert script and that's it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question