Registration

I have been scouring the Internet for some tutorial on how to register users using yii. I did find the user module, but found it too much for my current setup. This is how I attempted to register users on my site.

I modified the LoginForm and called it RegisterForm.php




<?php


/**

 * RegisterForm class.

 * RegisterForm is the data structure for keeping

 * user registration form data. It is used by the 'register' action of 'SiteController'.

 */

class RegisterForm extends CFormModel

{

	public $username;

	public $password;

	public $email;


	private $_identity;


	/**

	 * Declares the validation rules.

	 * The rules state that username, password & email are required,

	 * and username & email needs to be unique.

	 */

	public function rules()

	{

		return array(

			// username and password are required

			array('username, password, email', 'required'),

			// make sure username and email are unique

            array('username, email', 'unique'),

		);

	}


	/**

	 * Declares attribute labels.

	 */

	public function attributeLabels()

	{

		return array(

			'username'=>'Your username for the game',

			'password'=>'Your password for the game',

			'email'=>'Needed in the event of password resets',

		);

	}

}



And in SiteController.php, added this piece of code




	/**

	 * Displays the register page

	 */

	public function actionRegister()

	{

		$model=new RegisterForm;

		$newUser = new User;

		

		// 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['RegisterForm']))

		{

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

			$newUser->username = $model->username;

			$newUser->password = $model->password;

			$newUser->email = $model->email;

			$newUser->joined = date('Y-m-d');

				

			if($newUser->save()) {

				$identity=new UserIdentity($newUser->username,$model->password);

				$identity->authenticate();

				Yii::app()->user->login($identity,0);

				//redirect the user to page he/she came from

				$this->redirect(Yii::app()->user->returnUrl);

			}

				

		}

		// display the register form

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

	}



This works, as the user was created in the table and I could login / logout.

I know there is plenty of stuff that can be added like e-mail validation, captcha, etc.

But what I want to ask is it really so simple or am I doing something wrong?

Yes, it’s really that easy :D

It looks like you have forgotten to validate you form before creating the user using its data. Maybe controller should look like this:




    	/**

 		* Displays the register page

 		*/

    	public function actionRegister()

    	{

            	$model=new RegisterForm;

            	$newUser = new User;

            	

            	// 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['RegisterForm']))

            	{

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

                    	

                    	if ($model->validate()) {

                          	$newUser->username = $model->username;

                          	$newUser->password = $model->password;

                          	$newUser->email = $model->email;

                          	$newUser->joined = date('Y-m-d');

                                  	

                          	if($newUser->save()) {

                                  	$identity=new UserIdentity($newUser->username,$model->password);

                                  	$identity->authenticate();

                                  	Yii::app()->user->login($identity,0);

                                  	//redirect the user to page he/she came from

                                  	$this->redirect(Yii::app()->user->returnUrl);

                          	}

                    	}

                            	

            	}

            	// display the register form

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

    	}  

@MadAnd: Model validation will be pulled in by default if you call save(). save(false) prevents that (in case you explicitly called validate() previously. Like you’ve done in your code ;) )

Thanks Da:Sourcerer. :)

@MadAnd,

I started with having $model->validate(), but it returned an error:




RegisterForm and its behaviors do not have a method or closure named "tableName". 

So I removed that line, it fixed the error and also lead to a successful registration. :)

[size="2"]On save validates only the CActiveRecord but not the CFormModel! Please take care of this. So you have to validate your form of course.[/size]

[size="2"]Robert[/size]

Could you guide me with this?

I want the username to be unique, so have specified that in the rules.

Yes of course,

you have to assign the CActiveRecord class name of your user model as attribute in the unique validator:


array('username, email', 'unique', 'className' => 'User')

more about the unique validator stuff: http://www.yiiframew…UniqueValidator

… and you have to enable the validation before save in your controller:


if ($model->validate () && $newUser->save ())

Regards

Robert

Thanks Robert.

That did the trick!

I copied the code shown in the previous posts above and tried to get it to work but it just is not saving the data to the user table. It does validate but nothing happens when all input is correct.

Model




/**

 * RegisterForm class.

  */

class registerForm extends CFormModel

{

	public $username;

	public $password;

	public $first_name;

	public $last_name;

	public $email;

	

	private $_identity;


	/**

	 * Declares the validation rules.

	 * The rules state that username and password are required,

	 * and password needs to be authenticated.

	 */

	public function rules()

	{

		return array(

			// username and password are required

			array('username, password,first_name, last_name, email', 'required'),

			array('username, email', 'unique', 'className' => 'Users'),

			

		);

	}


	/**

	 * Declares attribute labels.

	 */

	public function attributeLabels()

	{

		 return array(

                        'first_name'=>'First Name',

			'last_name'=>'Last Name',

			'username'=>'Username',

                        'password'=>'Password',

                        'email'=>'Email',

						          

		  );


	}


}






Note that I did declare className=>Users in the unique validator section of rules

Site Controller method




 public function actionRegister()

        {

                $model = new registerForm;

                $newUser = new Users;

                

                // collect user input data

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

                {

				

		  if ($model->validate () && $newUser->save ())

		  {

                   

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

                        $newUser->first_name = $model->first_name;

			$newUser->last_name = $model->last_name;

			$newUser->username = $model->username;

                        $newUser->password = $model->password;

                        $newUser->email = $model->email;

                        $newUser->last_modified = date('Y-m-d');

                                

                         $identity=new UserIdentity($newUser->username,$newUser->password);

                         $identity->authenticate();

                         Yii::app()->user->login($identity,0);

                         //redirect the user to page he/she came from

                         $this->redirect(Yii::app()->user->returnUrl);

                   }

                                

                }//end if isset

				

				

                // display the register form

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

        }

		



Can anyone spot the error that is preventing it from working?

The problem is that, in controller, you try to save user model before filling it with data . Look at code sample on my previous post and adjust your code. This should resolve your issue.

Thanks for the quick response. The form is now saving but the validation of the unique email and username is still not working. My modified code is shown below:




public function actionRegister()

        {

                $model=new RegisterForm;

                $newUser = new User;

                

                // if it is ajax validation request

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

                {

                        echo CActiveForm::validate($model);

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

                }


                // collect user input data

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

                {

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

                        $newUser->username = $model->username;

                        $newUser->password = $model->password;

                        $newUser->email = $model->email;

			$newUser->first_name = $model->first_name;

			$newUser->last_name = $model->last_name;

			$newUser->type = "admin";

                        $newUser->last_modified = date('Y-m-d');

                        			

			if($newUser->save()) {

				  

                                $identity=new UserIdentity($newUser->username,$model->password);

                                $identity->authenticate();

                                Yii::app()->user->login($identity,0);

                                //redirect the user to page he/she came from

                                $this->redirect(Yii::app()->user->returnUrl);

								

							

                        }

                                

                }

                // display the register form

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

        }

		



I tried inserting if($model->validate()) after the isset($_POST[‘RegisterForm’]) command but when I did that, the whole thing bombed. Any ideas on this?

The check for validation should be performed after this line in your code:


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



Hello, I have create Register page and Login systems with Yii framework, but it is not working. There is no php or yii error, but it seems that registered users can’t sign in.This works, as the user was created in the table and I could not login / logout.

But what I want to ask is it really so simple or am I doing something wrong?

SiteController.php




public function actionRegister()

    {               

    	$model=new registration;

      


		 // 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['registration']))

		{

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

			

			if ($model->validate()) 

			{ 

				$newUser->username = $model->username;

          	  	$newUser->password = $model->password;

  		        $newUser->email = $model->email;

            	$newUser->firstname = $model->firstname;

            	$newUser->lastname = $model->lastname;

            	$newUser->last_modified = date('Y-m-d');

			

				if($model->save())

				{

					 $identity=new UserIdentity($newUser->username,$model->password);

                 	 $identity->authenticate();

                 	 Yii::app()->user->login($identity,0);

                 	//redirect the user to page he/she came from

                 	$this->redirect(Yii::app()->user->returnUrl);                                               

					$this->refresh();

			   }

		    }

		}

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

    }


protected/view/site/register.php

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>

<script type="text/javascript" src="js/jquery.dynDateTime.js"></script>

<script type="text/javascript" src="js/calendar-en.js"></script>

<script type="text/javascript">

	jQuery(document).ready(function() {

		jQuery("#dateDefault").dynDateTime(); //defaults

	});

</script>

<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/calendar-win2k-cold-1.css" /> 

 

 

<h1 style="color:#FFFFFF">Register</h1>

 

<p style="color:#FFFFFF">Please fill out the following form with your register credentials:</p>

 

<div class="form" style="color:#FFFFFF">

<?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,'username'); ?>

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

                 <div class="clear"></div>

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

        </div>

        

         <div class="row">

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

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

                 <div class="clear"></div>

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

        </div>

        

        <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,'firstname'); ?>

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

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

        </div>

        

        <div class="row">

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

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

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

        </div>

        

        <div class="row">

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

               <?php echo $form->textField($model,'birthdate',array('id'=>'dateDefault')); ?>

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

        </div>

 		

        <div class="row buttons">

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

        </div>

 

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

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

model/registration.php

 

<?php


/**

 * This is the model class for table "registration".

 *

 * The followings are the available columns in table 'registration':

 * @property integer $id

 * @property string $username

 * @property string $password

 * @property string $email

 * @property string $firstname

 * @property string $lastname

 * @property string $birthdate

 */

class registration extends CActiveRecord

{

	/**

	 * Returns the static model of the specified AR class.

	 * @param string $className active record class name.

	 * @return registration the static model class

	 */

	public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}


	/**

	 * @return string the associated database table name

	 */

	public function tableName()

	{

		return 'registration';

	}


	/**

	 * @return array validation rules for model attributes.

	 */

	public function rules()

	{

		// NOTE: you should only define rules for those attributes that

		// will receive user inputs.

		return array(

			array('username, password, email, firstname, lastname, birthdate', 'required'),

			array('username, password, email, firstname, lastname', 'length', 'max'=>100),

			// The following rule is used by search().

			// Please remove those attributes that should not be searched.

			array('id, username, password, email, firstname, lastname, birthdate', 'safe', 'on'=>'search'),

		);

	}


	/**

	 * @return array relational rules.

	 */

	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

		);

	}


	/**

	 * @return array customized attribute labels (name=>label)

	 */

	public function attributeLabels()

	{

		return array(

			'id' => 'ID',

			'username' => 'Username',

			'password' => 'Password',

			'email' => 'Email',

			'firstname' => 'Firstname',

			'lastname' => 'Lastname',

			'birthdate' => 'Birthdate',

		);

	}


	/**

	 * Retrieves a list of models based on the current search/filter conditions.

	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.

	 */

	public function search()

	{

		// Warning: Please modify the following code to remove attributes that

		// should not be searched.


		$criteria=new CDbCriteria;


		$criteria->compare('id',$this->id);

		$criteria->compare('username',$this->username,true);

		$criteria->compare('password',$this->password,true);

		$criteria->compare('email',$this->email,true);

		$criteria->compare('firstname',$this->firstname,true);

		$criteria->compare('lastname',$this->lastname,true);

		$criteria->compare('birthdate',$this->birthdate,true);


		return new CActiveDataProvider($this, array(

			'criteria'=>$criteria,

		));

	}

}



Plz Help Me

Thnks

Hi

I have to solve this Probelm …

As far as I can notice $newUser is undefined. Is it call to some other model? Or are you trying to create new object?

Use only $model and that is it, if it passes all the rules in the model validation it will save.

I think you’ve solved that problem lol

Guys

Please help, I am not able to submit my form variables and save it to database + there is no validation happening :(

Registration Model




class registerForm extends CFormModel

{

        public $username;

        public $password;

        public $email;


        private $_identity;


        /**

         * Declares the validation rules.

         * The rules state that username, password & email are required,

         * and username & email needs to be unique.

         */

        public function rules()

        {

                return array(

                        // username and password are required

                        array('username, password, email', 'required','message'=>'Required!'),

                        // make sure username and email are unique

            array('username, email', 'unique'),

                );

        }


        /**

         * Declares attribute labels.

         */

        public function attributeLabels()

        {

                return array(

                        'username'=>'Username',

                        'email'=>'Email Adress',

                        'Password'=>'Password',

                );

        }

}




CONTROLLER




public function actionRegister()

		{

			$model=new RegisterForm;

			$newUser = new TblUser;


                // if it is ajax validation request

			// if(isset($_POST['ajax']) && $_POST['ajax']==='verticalForm')

			// {

			// 	echo CActiveForm::validate($model);

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

			// }


				//echo $_POST['RegisterForm'];

                // collect user input data

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

			{

			


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

			

			if ($model->validate()) 

			{

					$newUser->Username = $model->username;

					$newUser->Password = $model->password;

					$newUser->Email = $model->email;

                    


					if($newUser->save()) 

								{

						$identity=new UserIdentity($newUser->Username,$model->Password);

						$identity->authenticate();

						Yii::app()->user->login($identity,0);

                                

						$this->redirect(Yii::app()->user->returnUrl);

								}

			}


			}

			

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

			

                // display the register form

			

		}



VIEW





div class="form">

<?php echo CHtml::beginForm(); ?>

    <?php echo CHtml::errorSummary($model); ?>

    <div class="row">

        <?php echo CHtml::activeLabel($model,'username'); ?>

        <?php echo CHtml::activeTextField($model,'username') ?>

</div>

    <div class="row">

        <?php echo CHtml::activeLabel($model,'email'); ?>

        <?php echo CHtml::activeTextField($model,'email') ?>

</div>

    <div class="row rememberMe">

        <?php echo CHtml::activeLabel($model,'password'); ?>

        <?php echo CHtml::activePasswordField($model,'password'); ?>

</div>

    <div class="row submit">

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

</div>

<?php echo CHtml::endForm(); ?>




Thanks I found solution already!