Answer the question
In order to leave comments, you need to log in
How to make a redirect in yii2 after user registration?
Good afternoon!
I can't figure out what's going on with Yii2..... I'm still learning, so don't be too angry with me.
I took a code from another site, it worked well, a person registered, entered data, pressed a button, and he was redirected to the main page and immediately authorized, this was the code:
public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
return $user->save() ? $user : null;
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
if($user->save()){
$role = Yii::$app->authManager->getRole('user');
Yii::$app->authManager->assign($role, $user->id_user);
}
}
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
return $this->goHome();
Answer the question
In order to leave comments, you need to log in
In short, as always, I did such a stupid thing ..... I didn’t add return to the form model ....... I wrote here, looked again and everything came up, sorry for the trouble.
If someone needs an answer, then here it is, you just had to add return to
public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
if($user->save()){
$role = Yii::$app->authManager->getRole('user');
Yii::$app->authManager->assign($role, $user->id_user);
}
return $user;
}
Good morning.
And you don't return anything in the signUp() method, that's why it doesn't work.
Compare what you had with what you have now.
In the first option you returned
In the second option you return nothing
if($user->save()){
$role = Yii::$app->authManager->getRole('user');
Yii::$app->authManager->assign($role, $user->id_user);
}
if($user->save()){
$role = Yii::$app->authManager->getRole('user');
Yii::$app->authManager->assign($role, $user->id_user);
return true;
}
else{
return false;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question