Change Password

i am new to YII framework. i am writing a simple method to change password, i am want to validate the controls like if blank then show the error message or if password and re-type password does not match then show error. i have used the below code to do this :

Here is my view file

<?php

/* @var $this SiteController */

/* @var $model LoginForm */

/* @var $form CActiveForm */

$this->pageTitle=Yii::app()->name . ’ - Change Password’;

$this->breadcrumbs=array(

'Change Password',

);

?>

<h1>Change Password</h1>

<div class="form">

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

'id'=&gt;'users-form',


'enableAjaxValidation'=&gt;true,

)); ?>

<?php

$flashMessages = Yii::app()->user->getFlashes();

if ($flashMessages) {

echo '&lt;ul class=&quot;flashes&quot;&gt;';


foreach(&#036;flashMessages as &#036;key =&gt; &#036;message) {


    echo '&lt;li&gt;&lt;div class=&quot;flash-' . &#036;key . '&quot;&gt;' . &#036;message . &quot;&lt;/div&gt;&lt;/li&gt;&#092;n&quot;;


}


echo '&lt;/ul&gt;';

}

?>

&lt;div class=&quot;row&quot;&gt;


    &lt;?php echo &#036;form-&gt;labelEx(&#036;model,'currentPassword'); ?&gt;


    &lt;?php echo &#036;form-&gt;passwordField(&#036;model,'currentPassword',array('size'=&gt;60,'maxlength'=&gt;100)); ?&gt;


    &lt;?php echo &#036;form-&gt;error(&#036;model,'currentPassword'); ?&gt;

</div>

<div class="row">

    &lt;?php echo &#036;form-&gt;labelEx(&#036;model,'newPassword'); ?&gt;


    &lt;?php echo &#036;form-&gt;passwordField(&#036;model,'newPassword',array('size'=&gt;60,'maxlength'=&gt;100)); ?&gt;


    &lt;?php echo &#036;form-&gt;error(&#036;model,'newPassword'); ?&gt;

</div>

<?php /*?><div class="row">

&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'newPassword'); ?&gt;


&lt;?php





&#036;this-&gt;widget('ext.EStrongPassword.EStrongPassword',


    array('form'=&gt;&#036;form, 'model'=&gt;&#036;model, 'attribute'=&gt;'newPassword'));?&gt;


&lt;?php echo &#036;form-&gt;error(&#036;model,'newPassword'); ?&gt;

</div>

<?php */?>

<div class="row">

    &lt;?php echo &#036;form-&gt;labelEx(&#036;model,'newPasswordRepeat'); ?&gt;


    &lt;?php echo &#036;form-&gt;passwordField(&#036;model,'newPasswordRepeat',array('size'=&gt;60,'maxlength'=&gt;100)); ?&gt;


    &lt;?php echo &#036;form-&gt;error(&#036;model,'newPasswordRepeat'); ?&gt;

</div>

&lt;div class=&quot;row buttons&quot;&gt;


	&lt;?php echo CHtml::submitButton('Change Password'); ?&gt;


&lt;/div&gt;

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

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

Here is my Model file :-

<?php

/**

  • This is the model class for table "tbl_users_master".

  • The followings are the available columns in table ‘tbl_users_master’:

  • @property integer $user_id

  • @property string $first_name

  • @property string $last_name

  • @property string $employee_code

  • @property string $username

  • @property string $password

  • @property string $role

  • @property string $joining_date

  • @property string $pending_regular_leave

  • @property string $pending_medical_leave

  • @property string $allocated_regular_leave

  • @property string $allocated_medical_leave

  • @property integer $is_active

*/

class Users extends AttendanceActiveRecord

{

 public &#036;currentPassword;


 public &#036;newPassword;


 public &#036;newPasswordRepeat;


 public &#036;verifyCode;





public static function model(&#036;className=__CLASS__)


{


	return parent::model(&#036;className);


}





public function tableName()


{


	return 'tbl_users_master';


}





public function getJoiningDate()


{


	return date(&quot;d-m-Y&quot;, strtotime(&#036;this-&gt;joining_date));


}








public function rules()


{


	return array(


		array('is_active', 'numerical', 'integerOnly'=&gt;true),


		array('first_name, joining_date,last_name, employee_code, username, password, role', 'required'),		


	    array('employee_code', 'numerical', 'integerOnly'=&gt;true),


		array('username','email'),		


		array('username','valid_username','on'=&gt;array('create')),


		


		//array('username', 'contraints', 'readOnly'=&gt;true, 'on'=&gt;'update'),


		


		array('currentPassword, newPassword, newPasswordRepeat', 'required','on'=&gt;array('change')),


		//array('newPassword', 'length', 'min' =&gt; 6, 'max'=&gt;20, 'message'=&gt;Yii::t(&quot;translation&quot;, &quot;{attribute} is too short.&quot;)),


		//array('newPassword','ext.SPasswordValidator.SPasswordValidator', 'preset' =&gt; 'strong', 'max' =&gt; 41),


		array('newPassword', 'compare', 'compareAttribute'=&gt;'newPasswordRepeat','on'=&gt;array('change')),


		array('currentPassword', 'equalPasswords','on'=&gt;array('change')),


		array('verifyCode', 'captcha', 'allowEmpty'=&gt;&#33;CCaptcha::checkRequirements(),'on'=&gt;array('forgotPassword')),


		array('joining_date', 'safe'),


		array('user_id, first_name, last_name, employee_code, username, password, role, joining_date, pending_regular_leave, pending_medical_leave, allocated_regular_leave, allocated_medical_leave, is_active', 'safe', 'on'=&gt;'search'),


	);


}








public function equalPasswords(&#036;attribute, &#036;params)


{


	&#036;user = Users::findByPk(Yii::app()-&gt;user-&gt;id);


	if (&#036;user-&gt;password &#33;= md5(&#036;this-&gt;currentPassword))


		&#036;this-&gt;addError(&#036;attribute, 'Old password is incorrect.');


}

public function valid_username($attribute,$params)

{

if(Users::model()-&gt;findByattributes(array('username'=&gt;&#036;this-&gt;username)))


{


&#036;this-&gt;addError('username',&quot;This email already exists&quot;);


}


return true;

}

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(


	'leaves' =&gt; array(self::HAS_MANY, 'Leaves', 'leave_id'),


	'creator' =&gt; array(self::BELONGS_TO, 'Users', 'user_id'),


	'updator' =&gt; array(self::BELONGS_TO, 'Users', 'user_id'),


	);


}





public function getFullName()


{


	return &#036;this-&gt;first_name.' '.&#036;this-&gt;last_name;


}








public function setDateFormat()


{


	&#036;this-&gt;created_date=date(&quot;d-m-Y h:i a&quot;, strtotime(&#036;this-&gt;created_date));


	&#036;this-&gt;modified_date=date(&quot;d-m-Y h:i a&quot;, strtotime(&#036;this-&gt;modified_date));


	&#036;this-&gt;joining_date=date(&quot;d-m-Y&quot;, strtotime(&#036;this-&gt;joining_date));


}

public function RandomString($length)

{

if(&#33;is_int(&#036;length)||&#036;length&lt;1)


{


	trigger_error('Invalid length for random string');


	exit();


}


&#036;chars=&quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789&quot;;





&#036;randstring='';


&#036;str = '';


&#036;maxvalue=strlen(&#036;chars)-1;





for(&#036;i=0;&#036;i&lt;&#036;length;&#036;i++) &#036;randstring.=substr(&#036;chars,rand(0,&#036;maxvalue),1);


&#036;str = strtoupper(substr(md5(&#036;randstring),1,&#036;length));


return &#036;str;

}

public function attributeLabels()


{


	return array(


		'user_id' =&gt; 'User',


		'first_name' =&gt; 'First Name',


		'last_name' =&gt; 'Last Name',


		'employee_code' =&gt; 'Employee Code',


		'username' =&gt; 'Email',


		'password' =&gt; 'Password',


		'role' =&gt; 'Role',


		'joining_date' =&gt; 'Joining Date',


		'pending_regular_leave' =&gt; 'Pending Regular Leave',


		'pending_medical_leave' =&gt; 'Pending Medical Leave',


		'allocated_regular_leave' =&gt; 'Allocated Regular Leave',


		'allocated_medical_leave' =&gt; 'Allocated Medical Leave',


		'is_active' =&gt; 'Is Active',


		'currentPassword' =&gt; 'Old Password',


		'newPassword' =&gt; 'New Password',


		'newPasswordRepeat' =&gt; 'Confirm Password',


		'verifyCode'=&gt;'Verification Code',


		'created_date'=&gt; 'Created On',


		'modified_date'=&gt;'Modified On',


		'created_ip'=&gt;&quot;Created by IP&quot;,


		'modified_ip'=&gt;&quot;Modified by IP&quot;,


	);


}





public function AddRegularLeaves(&#036;hours,&#036;isPermitted)


{


	if(&#036;isPermitted==1)


	{


		&#036;this-&gt;allocated_regular_leave = &#036;this-&gt;allocated_regular_leave + &#036;hours;


		&#036;this-&gt;update();


	}


}





public function SubtractRegularLeaves(&#036;hours,&#036;isPermitted)


{


	if(&#036;isPermitted==1)


	{


		&#036;this-&gt;allocated_regular_leave = &#036;this-&gt;allocated_regular_leave - &#036;hours;


		&#036;this-&gt;update();


	}


}





public function AddMedicalLeaves(&#036;hours,&#036;isPermitted)


{


	if(&#036;isPermitted==1)


	{


		&#036;this-&gt;allocated_medical_leave = &#036;this-&gt;allocated_medical_leave + &#036;hours;


		&#036;this-&gt;update();


	}


}





public function SubtractMedicalLeaves(&#036;hours,&#036;isPermitted)


{


	if(&#036;isPermitted==1)


	{


		&#036;this-&gt;allocated_medical_leave = &#036;this-&gt;allocated_medical_leave - &#036;hours;


		&#036;this-&gt;update();


	}


}








public function searchWithRelated() {


    &#036;criteria = new CDbCriteria;





    &#036;criteria-&gt;together = true;


    &#036;criteria-&gt;with = array('user');      


    &#036;criteria-&gt;compare('leaves.user_id',&#036;this-&gt;user_id, true);





    return new CActiveDataProvider(&#036;this, array(


        'criteria' =&gt; &#036;criteria,


        'pagination' =&gt; array(


            'pageSize' =&gt; 1,


        ),


    ));


}














public function search()


{


	&#036;criteria=new CDbCriteria;


	&#036;criteria-&gt;compare('user_id',&#036;this-&gt;user_id);





	&#036;criteria-&gt;compare('first_name',&#036;this-&gt;first_name,true);


	&#036;criteria-&gt;compare('last_name',&#036;this-&gt;last_name,true);


	&#036;criteria-&gt;compare('employee_code',&#036;this-&gt;employee_code,true);


	&#036;criteria-&gt;compare('username',&#036;this-&gt;username,true);


	&#036;criteria-&gt;compare('password',&#036;this-&gt;password,true);


	&#036;criteria-&gt;compare('role',&#036;this-&gt;role,true);


	&#036;criteria-&gt;compare('joining_date',&#036;this-&gt;joining_date,true);


	&#036;criteria-&gt;compare('pending_regular_leave',&#036;this-&gt;pending_regular_leave,true);


	&#036;criteria-&gt;compare('pending_medical_leave',&#036;this-&gt;pending_medical_leave,true);


	&#036;criteria-&gt;compare('allocated_regular_leave',&#036;this-&gt;allocated_regular_leave,true);


	&#036;criteria-&gt;compare('allocated_medical_leave',&#036;this-&gt;allocated_medical_leave,true);


	&#036;criteria-&gt;compare('is_active',&#036;this-&gt;is_active);





	return new CActiveDataProvider(&#036;this, array(


		'pagination' =&gt; array('pageSize' =&gt; 2),


		'criteria'=&gt;&#036;criteria,


	));


}

}

Here is my Controller file :-

public function actionChange()

{

&#036;model=new Users;


&#036;model-&gt;scenario='change';


if (isset(&#036;_POST['Users'])) {


    &#036;model-&gt;setAttributes(&#036;_POST['Users']);                     





    if(&#036;model-&gt;validate())


        {


            print &quot;true&quot;;   


        }


    else{





            print &quot;false&quot;;  


        }   





    if(&#036;model-&gt;validate())


        {       


            &#036;pass = md5(&#036;_POST['Users']['newPassword']);            


            &#036;userModel = Users::model()-&gt;findByPk(Yii::app()-&gt;user-&gt;id);


            &#036;userModel-&gt;password = &#036;pass; 


            &#036;data = &#036;userModel-&gt;update();


        }





        if(isset(&#036;data))


        {


            Yii::app()-&gt;user-&gt;setFlash('success',&quot;Password changed successfully&#33;&quot;);


            &#036;this-&gt;redirect(array('Users/change'), true);


        }


    }

$this->render(‘change_password’, array(‘model’=>$model,true));

}

But $model->validate() always returns false to me either i fill the fields or not.

please help me.

It’s hard to follow your code without using the forums code tags, but are you seeing the error summary in the view when the validation fails? The code


<?php echo $form->errorSummary($model); ?>

inside your view would tell what didn’t validate. From there you can narrow down what the problem is.

Follow this wiki to find best solution -

Change Password with TbActiveForm