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
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')
}],
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With