D
D
Doniyor Mamatkulov2016-07-13 09:58:30
Yii
Doniyor Mamatkulov, 2016-07-13 09:58:30

Login uniqueness when editing a user?

Hey!
I use Yii2 and write user management. With this function in the model I check the login for uniqueness

public function checkUniqueness($attribute, $params)
    {
        $data = self::find()->where(['alive'=>1, 'name'=>$this->login])->all();
        if(!empty($data)) {
            $this->addError($attribute, Yii::t('app', 'This login is occupied'));
        }
    }

Rules is like this:
['login', 'checkUniqueness', 'on' => self::SCENARIO_INSERT],

But when editing, you can easily enter any existing login. How to avoid it?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
Антон, 2016-07-13
@karminski

А чем вас не устраивает встроенный валидатор unique?

Александр, 2016-07-13
@p0vidl0

Примерно такая проверка для всех сценариев:

$collision = self::find()->where(['and', ['alive' => 1], ['name' => $this->login], ['!=', 'id', $this->id]])->count();
if ($collision > 0) {
    ...
}

T
Toey, 2016-07-13
@Toey

для проверки уникальности если использовать валидатор свой
можно так

public function checkUniqueness($attribute, $params)
{
    $data = self::find()->where([ 'name'=>$this->login])->one();
    if(!is_null($data)){
         $this->addError($attribute, Yii::t('app', 'This login is occupied'));
    }        
}

на не нужно выбирать все записи нам надо знать если хотя бы одна с таким логином.
или использовать uniquevalidator

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question