passing variables between controllers

Hi all,

I’m new to Yii and OOP. I have a registration form where people can register. It is in the controller UserController and linked to tbl_user. After registration, the user gets redirected to a login form / actionLogin in SiteController. To make it a bit user friendlier, the registered email is passed on in the URL, fetched by the actionLogin in SiteController and put in the email field of the login form in the view. However, I heard this should be avoided as it is not very secure to retrieve parameters from the URL. Is there another way to save the email and retrieve it from another controller?

I guess I can’t really save it in $model->email (instance of User) because when the login form gets loaded, $model is overwritten with an instance of LoginForm. I guess I could create a new class with just that value that is than accessible across different controllers but I have a feeling that there is an easier solution?

Any help is much appreciated.

actionRegister in UserController




public function actionRegister()

	{


                // create new instance of User

		$model=new User;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['User']))

		{

			// for model validation rules

                        // only 3 required fields for this scenario whereas update form has more required fields

                        // see model User for more details

			$model->setScenario('register');

			

			$model->attributes=$_POST['User'];

			

			if($model->save())

				

                                // pass on registered=1 through URL for message "Thanks for registering" on login form

				// pass on email through URL for more convenient login on login form				

                                // CHECK: is there a way to

                                

                                $this->redirect(array('site/login','registered'=>'1','email'=>$model->email));

                                

                                //$this->redirect('index.php?r=site/login');

		}


		$this->render('register',array(

			'model'=>$model,

		));

	}	



actionLogin in SiteController


	public function actionLogin()

	{

		$model=new LoginForm;


		// check URL for whether user came from index.php?r=user/register, convert variable into integer for security reason

		if (!empty($_GET['registered']))

		{

			// publich $registered set in model			

			$model->registered = (int) $_GET['registered'];


			// GET email address from URL and put it in as default value in the form of the view file for more convenient login

			if ( isset($_GET['email']) )

			{

				$model->email = strip_tags($_GET["email"]);

			} else {

				$model->email = "";

			}


		} else {

			$model->registered = 0;

		}		


		// if it is ajax validation request

		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')

		{

			echo CActiveForm::validate($model);

			Yii::app()->end();

		}


		// collect user input data

		if(isset($_POST['LoginForm']))

		{

			$model->attributes=$_POST['LoginForm'];

			// validate user input and redirect to the previous page if valid

			if($model->validate() && $model->login())

				$this->redirect('index.php?r=user/index');

		}

		// display the login form

		$this->render('login',array('model'=>$model));

	}

u can

save the newly registered user’s id or email-id in the SESSION on successful registration and in login check if that SESSION var exist, fetch its value & destroy SESSION var.

cheers,

Thanks, worked. Here the code for people visiting this post in the future:

UserController for Registration:


	 /** Registering new user

	 * Creates a new model.

	 * If registration is successful, the browser will be redirected to the login page.

	 */

	public function actionRegister()

	{


                // create new instance of User

		$model=new User;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


                // for model validation rules

                // only 3 required fields for this scenario whereas update form has more required fields

                // see model User for more details

                $model->setScenario('register');


                if(isset($_POST['User']))

		{

			

			$model->attributes=$_POST['User'];

			

			// pass email from registration (UserController) form to login (SiteController) form

                        // destroy session after login

                        $emailFromRegistrationForm=new CHttpSession;

                        $emailFromRegistrationForm->open();

                        $emailFromRegistrationForm['email'] = strip_tags($model->email);


                        if($model->save())

				                             

                                

                                

                              $this->redirect('index.php?r=site/login');

		}


		$this->render('register',array(

			'model'=>$model,

		));

	}

SiteController for logging in


	/**

	 * Displays the login page

	 */

	public function actionLogin()

	{

		$model=new LoginForm;


                // pass email from registration (UserController) form to login (SiteController) form

                // destroy session after login

                $emailFromRegistrationForm=new CHttpSession;

                $emailFromRegistrationForm->open();

                $model->email = strip_tags($emailFromRegistrationForm['email']);

                


		// if it is ajax validation request

		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')

		{

			echo CActiveForm::validate($model);

			Yii::app()->end();

		}


		// collect user input data

		if(isset($_POST['LoginForm']))

		{

			$model->attributes=$_POST['LoginForm'];

			// validate user input and redirect to the previous page if valid

			if($model->validate() && $model->login())


                                // pass email from registration (UserController) form to login (SiteController) form

                                // destroy session after login

                                $emailFromRegistrationForm->close();

                                $emailFromRegistrationForm->destroy();


                                $this->redirect('index.php?r=user/index');

		}

		// display the login form

		$this->render('login',array('model'=>$model));

	}

Correct but should not save email to session if the registration failed, so only if model saved successfully.

like this:


                if(isset($_POST['User']))

		{

			$model->attributes=$_POST['User'];


                        if($model->save()){

			   // pass email from registration (UserController) form to login (SiteController) form

                           // destroy session after login

                           $emailFromRegistrationForm=new CHttpSession;

                           $emailFromRegistrationForm->open();

                           $emailFromRegistrationForm['email'] = strip_tags($model->email);

	                     

                              $this->redirect('index.php?r=site/login');

                      }

		}



Yeah, I tried that before but when filling out the form so it doesn’t validate (e.g. not filling out all required fields), a PHP error occurs: Undefined variable: emailFromRegistrationForm . How can I solve this? Thx

u see the problem is if u keep if outside if($model->save()){…} and

registration failed but email field is filled, u have still saved the email in the session, & now if the user click on login u will use that email id to login even when no registration exist with that email (if not already registered earlier, unique validator error occured).

u will get error here, if reg’n failed, as in this case email is not saved in the session & u were not checking whether it exist there or not.

change this in the SiteController for logging in


public function actionLogin(){

...

if(isset($emailFromRegistrationForm['email']))

    $model->email = strip_tags($emailFromRegistrationForm['email']);


...

}

Thanks. Here the code for future visitors of this post:

UserController:




	public function actionRegister()

	{


                // create new instance of User

		$model=new User;


		// Uncomment the following line if AJAX validation is needed

		$this->performAjaxValidation($model);


                // for model validation rules

                // only 3 required fields for this scenario whereas update form has more required fields

                // see model User for more details

                $model->setScenario('register');




                if(isset($_POST['User']))

		{


                 

                    $model->attributes=$_POST['User'];




                        if($model->save()) {

			                             

                            // if not done previously (i.e. form validation didn't pass and form gets reloaded)

                            if(!(isset($emailFromRegistrationForm['email']))) {

                                // pass email from registration (UserController) form to login (SiteController) form

                                // destroy session after login

                                $emailFromRegistrationForm=new CHttpSession;

                                $emailFromRegistrationForm->open();

                                $emailFromRegistrationForm['email'] = strip_tags($model->email);

                            }

                                

                              $this->redirect('index.php?r=site/login');


                        }

                        

		}


		$this->render('register',array(

			'model'=>$model,

		));

	}



SiteController:




public function actionLogin()

	{

		$model=new LoginForm;


                // pass email from registration (UserController) form to login (SiteController) form

                // destroy session after login

                $emailFromRegistrationForm=new CHttpSession;

                $emailFromRegistrationForm->open();

                $model->email = strip_tags($emailFromRegistrationForm['email']);

                


		// if it is ajax validation request

		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')

		{

			echo CActiveForm::validate($model);

			Yii::app()->end();

		}


		// collect user input data

		if(isset($_POST['LoginForm']))

		{

			$model->attributes=$_POST['LoginForm'];

			// validate user input and redirect to the previous page if valid

			if($model->validate() && $model->login())


                                // pass email from registration (UserController) form to login (SiteController) form

                                // destroy session after login

                                $emailFromRegistrationForm->close();

                                $emailFromRegistrationForm->destroy();


                                $this->redirect('index.php?r=user/index');

		}

		// display the login form

		$this->render('login',array('model'=>$model));

	}




The login view:


<h1>Login</h1>


<?php


// pass email from registration (UserController) form to login (SiteController) form

if ( $model->email )

{

	?><p>You successfully registered with your email address <strong><?php echo $model->email ?></strong></p><?php

}

?>


<p>Please fill out the following form with your login credentials:</p>


<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'login-form',

	'enableAjaxValidation'=>true,

)); ?>


	<p class="note">Fields with <span class="required">*</span> are required.</p>


	<div class="row">

		<?php echo $form->labelEx($model,'email'); ?>

		<?php echo $form->textField($model,'email'); ?>

		<?php echo $form->error($model,'email'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'password'); ?>

		<?php echo $form->passwordField($model,'password'); ?>

		<?php echo $form->error($model,'password'); ?>

	</div>


	<!--<div class="row rememberMe">

		<?php echo $form->checkBox($model,'rememberMe'); ?>

		<?php echo $form->label($model,'rememberMe'); ?>

		<?php echo $form->error($model,'rememberMe'); ?>

	</div>-->


	<div class="row buttons">

		<?php echo CHtml::submitButton('Login'); ?>

	</div>


<?php $this->endWidget(); ?>

</div><!-- form -->


<p>New to XXX? Click <?php echo CHtml::link("here",array('user/register')); ?> here to create an account. It's free and easy.</p>