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.

Machavity
  • 30,841
  • 27
  • 92
  • 100
SADi
  • 295
  • 2
  • 12
  • 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 Nov 08 '16 at 12:43

2 Answers2

7

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,596
  • 1
  • 20
  • 42
user3265030
  • 194
  • 1
  • 3
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,747
  • 10
  • 38
  • 53
  • 4
    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