So I tackled this problem today and this was my solution. I made a register action in my siteController and made a clickable link on my main page. Made the form requesting name, password twice and then email. Here is that code:
<?php $this->pageTitle=Yii::app()->name . ' - Register'; ?>
<h1>Register</h1>
<div class="yiiForm">
<?php echo CHtml::form(); ?>
<?php echo CHtml::errorSummary($form); ?>
<div class="simple">
<?php echo CHtml::activeLabel($form,'username'); ?>
<?php echo CHtml::activeTextField($form,'username') ?>
</div>
<div class="simple">
<?php echo CHtml::activeLabel($form,'password'); ?>
<?php echo CHtml::activePasswordField($form,'password') ?>
</div>
<div class="simple">
<?php echo CHtml::activeLabel($form,'password_repeat'); ?>
<?php echo CHtml::activePasswordField($form,'password_repeat') ?>
</div>
<div class="simple">
<?php echo CHtml::activeLabel($form,'email'); ?>
<?php echo CHtml::activeTextField($form,'email') ?>
</div>
<br/>
<?php echo CHtml::submitButton('Register'); ?>
</div>
</form>
</div>
thats my register.php file.
I made a RegisterForm class:
<?php
class RegisterForm extends CFormModel
{
public $username;
public $password;
public $password_repeat;
public $email;
public function rules()
{
return array(
array('username, password, email', 'required'),
array('password_repeat', 'required', 'on'=>'register'),
array('password', 'compare', 'on'=>'register'),
array('username', 'register'),
);
}
public function register()
{
if(!$this->hasErrors()) // we only want to authenticate when no input errors
{
$username=strtolower($this->username);
$criteria = new CDbCriteria;
$criteria->select='username'; // only select the 'username' column
$criteria->condition='username=:username';
$criteria->params=array(':username'=>$this->username);
$user = user::model()->find($criteria);
// Check if username has already been registered
if ($user == null)
{
$user = new User;
$user->username = $this->username;
$user->password = md5($this->password);
$user->email = $this->email; // needs a validation check
$user->save();
$identity=new UserIdentity($this->username,$this->password);
$identity->authenticate();
$duration = 3600*24*30;
Yii::app()->user->login($identity,$duration);
} else {
$this->addError('username','Username is already taken');
}
}
}
}
This stops a username being registered twice and also logs the user in after registering. This all works, but I am wondering is this an ok / the right way to do this?
Any comments are welcome!