2011-11-21 69 views
4

林不知道注册后用户如何可以使用Yii框架登录用户HES创建后。如何登录在警予

在UserController的我为了让用户创建一个新帐户,那么在这里如果用户成功保存到数据库,我想瓶坯登录该用户藏汉创建的actionRegister。我的继承人代码:

public function actionRegister() 
    { 
     $model=new User; 

     if(isset($_POST['User'])) 
     { 
      $model->attributes=$_POST['User']; 

      if($model->save()){    

       $identity=new UserIdentity($model->email,$model->password); 
       $identity->authenticate(); 
       Yii::app()->user->login($identity); 

       $this->redirect(array('view','id'=>$model->id));     
      } 
     } 
     $this->render('register',array('model'=>$model)); 
    } 

预先感谢您的任何帮助ü可以给我在这件事情。

+0

这是不工作?这段代码运行时会发生什么? –

+0

刚刚在调用$ identity-> authenticate()之后检查了$ identity-> errorCode的值吗? –

回答

3

好了,好像我回答我的问题...

原来,$this->redirect(array('view','id'=>$model->id));没有让登录发生了一些模糊的原因......我不能回答,因为我开始学习yii昨天,但如果有知识的人可以证明这一点,我将不胜感激。

因此,解决办法只是移除重定向,我们得到了登录的用户帐户创建后的用户。

感谢您想帮助约翰和Jay =)

+1

控制器重定向是即时的。您可以指定一个布尔值作为第二个参数来禁用该方面。 – lucifurious

3

我解决了这个通过添加一些代码来UserIdentity类:

class UserIdentity extends CUserIdentity 
{ 
    private $_id; 

    //... 

    public function setUpUser($user_id) 
    { 
     $this->_id=$user_id; 
    } 
} 

因此,设置id在CUserIdentity情况下,你不需要验证它。只要这样做:

$identity=new UserIdentity($model->email,''); 
$identity->setUpUser($id); // id of user 
Yii::app()->user->login($identity); 

就是这样。

1

而不是删除$this->redirect(...);或使用第二个参数的

重定向(...,$终止 = TRUE,...)
$终止 - 是否终止当前应用程序在调用这个方法之后。默认为true。

你也可以把$this->redirect(...); if语句下,像这样:

if($model->save()) { 
    $identity=new UserIdentity($email,$password); 
    $identity->authenticate(); 
    if(Yii::app()->user->login($identity)) 
     $this->redirect(array('account/profile','id'=>$model->id)); 
} 

但是,当然,这不是最终的解决方案,你可能需要在个别情况下使用else为好。

还使用$this->redirect(..., false);与第二个参数也适用,谢谢lucifurious

$this->redirect(array('account/profile','id'=>$model->id), false);