Change Password with TbActiveForm

You are viewing revision #5 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#6) »

In this wiki I will show how could use a TbActiveForm for changing the old password.

In your models (User model)

//Define public variable
	public $old_password;
	public $new_password;
	public $repeat_password;
	//Define the rules for old_password, new_password and repeat_password with changePwd Scenario.
	public function rules()
	  return array(
		array('old_password, new_password, repeat_password', 'required', 'on' => 'changePwd'),
		array('old_password', 'findPasswords', 'on' => 'changePwd'),
		array('repeat_password', 'compare', 'compareAttribute'=>'new_password', 'on'=>'changePwd'),
	//matching the old password with your existing password.
	public function findPasswords($attribute, $params)
		$user = User::model()->findByPk(Yii::app()->user->id);
		if ($user->password != md5($this->old_password))
			$this->addError($attribute, 'Old password is incorrect.');

In your controller/action

public function actionChangepassword($id)
	$model = new User;

	$model = User::model()->findByAttributes(array('id'=>$id));

		$model->attributes = $_POST['User'];
		$valid = $model->validate();
		  $model->password = md5($model->new_password);
			 $this->redirect(array('changepassword','msg'=>'successfully changed password'));
			 $this->redirect(array('changepassword','msg'=>'password not changed'));


In your view file (changepassword.php)

<div class="form">

<?php $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
			'id' => 'chnage-password-form',
			'enableClientValidation' => true,
			'htmlOptions' => array('class' => 'well'),
			'clientOptions' => array(
				'validateOnSubmit' => true,

  <div class="row"> <?php echo $form->labelEx($model,'old_password'); ?> <?php echo $form->passwordField($model,'old_password'); ?> <?php echo $form->error($model,'old_password'); ?> </div>

  <div class="row"> <?php echo $form->labelEx($model,'new_password'); ?> <?php echo $form->passwordField($model,'new_password'); ?> <?php echo $form->error($model,'new_password'); ?> </div>

  <div class="row"> <?php echo $form->labelEx($model,'repeat_password'); ?> <?php echo $form->passwordField($model,'repeat_password'); ?> <?php echo $form->error($model,'repeat_password'); ?> </div>

  <div class="row submit">
    <?php $this->widget('bootstrap.widgets.TbButton', array('buttonType' => 'submit', 'type' => 'primary', 'label' => 'Change password')); ?>
  <?php $this->endWidget(); ?>

It's working fine...