0

I want my app to detect when a username is already taken and change it. In fact, when the user register himself he enter his last and first name and the username is lastName.firstName. How do I detect the username is already taken and how to change it (add a number for example) ?

Thanks.

Samaël Villette
  • 318
  • 3
  • 25

2 Answers2

1

So you should override beforeValidate() function, bellow is my sample code:

/**
 * @inheritdoc
 */
public function beforeValidate()
{
    /** your code here **/

    $isExist = static::find()->where(['username' => $this->username])->count();

    if($isExist){
        //Count total rows with the similar username
        $total = static::find()->where(['LIKE','username', "{$this->username}%"])->count();
        //We will add $total + 1 to the username so we have new unique username
        $this->username .= '-' . ($total+1); 
    }

    return parent::beforeValidate();
}
Jimmy Hoang
  • 36
  • 1
  • 6
0

What is the user module you use? Is it dektrium/yii2-user module?

We can override the user model class and override beforeValidate function to detect and change the username before save.

Jimmy Hoang
  • 36
  • 1
  • 6