Search code examples
yii2yii2-basic-apprbac

Yii2: Adding assign role in signup models


I am using Yii2 basic template and I want to assign role when a user signs up.

Please check the following code:

public function signup()
{
    if (!$this->validate()) {
        return null;
    }

    $user = new User();
    $user->fname = $this->fname;
    $user->mname = $this->mname;
    $user->lname = $this->lname;
    $user->address = $this->address;
    $user->username = $this->username;
    $user->email = $this->email;
    $user->setPassword($this->password);
    $user->generateAuthKey();

    $auth = new DbManager;
    $auth->init();
    $getrole = $auth->getRole($this->role);
    $auth->assign($getrole, Yii::$app->user->id);

    return $user->save() ? $user : null;
}

Now, the problem here is that when a user signs up, user data will be saved and new assignment is inserted but user ID is incorrect.


Solution

  • You need to know user ID to attach role to it, and you can't know it before saving user to database. So you need to save user first and the assign role using ID from saved model:

    if ($user->save()) {
        $auth = new DbManager;
        $auth->init();
        $getrole = $auth->getRole($this->role);
        $auth->assign($getrole, $user->id);
    
        return $user;
    }