Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

skip yii2 unique validation on update action if new value equals to prev value

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

like image 506
SADi Avatar asked Nov 08 '16 11:11

SADi


1 Answers

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')
}],
like image 87
user3265030 Avatar answered Oct 11 '22 17:10

user3265030