6

Because of unique validator get error on update action ('this username is already taken') i wanna validate username on update action when new username value not equals to prev value, it's my rule:

        [['username'], 'unique', 'on'=>'update', 'when' => function($model){
                return static::getOldUsername($model->id) !== $model->username;
            }
        ],

and it's my function to get prev username value:

public static function getOldUsername($id)
{
    return static::findIdentity($id)->username;
}

but it doesn't work, i think $model->getId() return nothing because of with static id (e.g: 23) its work.

        [['username'], 'unique', 'on'=>'update', 'when' => function($model){
                return static::getOldUsername(23) !== $model->username;
            }
        ],

how can i get model id? or if you have other ways to skip yii2 unique validation on update action if new value equals to prev value, please explain it.

thanks in advance

SADi
  • 195
  • 1
  • 12

3 Answers3

6

I think you can use $user->isAttributeChanged('username');

Example (I'm not testing this code):

[['username'], 'unique', 'on'=>'update', 'when' => function($model){
    return $model->isAttributeChanged('username')
}],
RavatSinh Sisodiya
  • 1,538
  • 1
  • 18
  • 38
user3265030
  • 184
  • 1
  • 3
2

i should say that my code is right and it works good now, error comes from a ,. Oops!!

I hope this question be useful for other viewers, thanks.

SADi
  • 195
  • 1
  • 12
0
[
    'login', 'unique', 
    'targetAttribute' => ['login'], 
    'filter' => ['!=', 'id', Yii::$app->request->get('id')], 
    'targetClass' => '\app\models\User', 
    'message' => 'This login has already been taken.',
],
Leonardo Alves Machado
  • 2,481
  • 7
  • 31
  • 43
  • 2
    While this code may answer the question, providing additional context regarding **how** and/or **why** it solves the problem would improve the answer's long-term value. – Alexander Mar 27 '18 at 14:12