Setting Null Value In Afterfind Function Not Working For Password Field

I have a user update form in which I am validating for password. If password is not blank, I am updating that password in db.

To set null value in form, I have write following code in model’s AfterFind function.

5791

Selection_009.png

But in update form, Value is set to it’s actual value in db. I have also try to set the value to null just above the password field, but it’s not working.

5792

Selection_010.png

I am using using vesrion 1.1.14

Any suggestion?

Hello Akshay Vanjare ,

Don’t use afterfind function,

Use this,

Load Model with blank value.


public function actionUpdate($id)

{


		$model=$this->loadModel($id,'User');

               $model->password    = '';

}

Thanks Yatin for your reply.

I also try your suggestion but it’s also not working. The problem only occurring for 75% records. for some records it’s apply afterfind method and your method also, but I don’t know the reason for other 75% why it’s not working.

Can you post your action and your model code? Use the editor’s code tags .

Here is the model code


<?php


/**

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

 *

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

 * @property integer $USER_ID

 * @property string $EMAIL

 * @property string $PASSWORD

 * @property string $USER_TYPE

 * @property integer $HOTEL_ID

 * @property string $FIRST_NAME

 * @property string $LAST_NAME

 * @property string $USER_STATUS

 * @property double $CREATED_ON

 * @property double $UPDATED_ON

 */

class User extends CActiveRecord

{

	public $REPEAT_PASSWORD;

	public $INIT_PASSWORD;

	public $assignee_name;

	/**

 	* @return string the associated database table name

 	*/

	public function tableName()

	{

		return 'tbl_user_master';

	}


	/**

 	* @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('EMAIL, USER_TYPE, FIRST_NAME, LAST_NAME, USER_STATUS', 'required'),

			array('HOTEL_ID', 'numerical', 'integerOnly'=>true),

			array('EMAIL', 'email'),

			array('EMAIL', 'unique'),

        	array('PASSWORD, REPEAT_PASSWORD', 'required', 'on'=>'insert'),

        	array('PASSWORD, REPEAT_PASSWORD', 'length', 'min'=>6, 'max'=>40),

        	array('PASSWORD', 'compare', 'compareAttribute'=>'REPEAT_PASSWORD'),

			array('CREATED_ON, UPDATED_ON', 'numerical'),

			array('HOTEL_ID', 'validhotel'),

			array('EMAIL, FIRST_NAME, LAST_NAME', 'length', 'max'=>50),

//			array('PASSWORD', 'length', 'max'=>32),

			array('USER_TYPE', 'length', 'max'=>5),

			array('USER_STATUS', 'length', 'max'=>1),

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

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

			array('USER_ID, EMAIL, PASSWORD, USER_TYPE, HOTEL_ID, FIRST_NAME, LAST_NAME, USER_STATUS', 'safe', 'on'=>'search'),

		);

	}


	public function validhotel($attribute,$params) {

    	if(!($this->USER_TYPE == 'admin' || $this->USER_TYPE == 'cro') && empty($this->$attribute)) {

        	$this->addError($attribute, 'Please select Hotel');

    	}

    	return true;

	}





	/**

 	* @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(

        	'hotel' => array(self::BELONGS_TO, 'Hotel', 'HOTEL_ID'),

        	'invoice' => array(self::HAS_MANY, 'Invoice', 'USER_ID'),

		);

	}


	public function defaultScope()

	{

    	$data = array();


    	if(! Yii::app()->user->isGuest) {

        	if(Yii::app()->user->user_type == "admin" || Yii::app()->user->user_type == "cro")  {

        	}   elseif(Yii::app()->user->user_type == "hotel")  {   	//if user is hotel user, show all user in that hotel

            	$data = array(

                	'condition' => $this->getTableAlias(false, false).'.HOTEL_ID=:hotel_id AND ('.$this->getTableAlias(false, false).'.USER_TYPE = (:utype) OR '.$this->getTableAlias(false, false).'.USER_TYPE = (:utype2))',

                	'params' => array(

                    	':hotel_id' => Yii::app()->user->hotel_id,

                    	':utype' => 'hotel',

                    	':utype2' => 'sale'

                	)

            	);

        	}   else   {   	//if user is sale person, show only sale persons account

            	$data = array(

                	'condition' => $this->getTableAlias(false, false).'.HOTEL_ID=:hotel_id AND '.$this->getTableAlias(false, false).'.USER_ID=:user_id',

                	'params' => array(

                    	':hotel_id' => Yii::app()->user->hotel_id,

                    	':user_id' => Yii::app()->user->user_id

                	)

            	);

        	}

    	}


    	return $data;

	}


	public function hotelAdmin($hotel_id = 0)

	{

    	$this->getDbCriteria()->mergeWith(array(

        	'condition'=>$this->getTableAlias(false, false).'.HOTEL_ID=:hotel_id AND '.$this->getTableAlias(false, false).'.USER_TYPE=:utype',

        	'params' => array(

            	':hotel_id' => $hotel_id,

            	':utype' => 'hotel'

        	)

    	));

    	return $this;

	}


	/**

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

 	*/

	public function attributeLabels()

	{

		return array(

			'USER_ID' => 'User',

			'EMAIL' => 'Email',

			'PASSWORD' => 'Password',

			'USER_TYPE' => 'User Type',

			'HOTEL_ID' => 'Hotel',

			'FIRST_NAME' => 'First Name',

			'LAST_NAME' => 'Last Name',

			'USER_STATUS' => 'User Status',

			'CREATED_ON' => 'Created On',

			'UPDATED_ON' => 'Updated On',

		);

	}




	protected function beforeValidate() {

    	foreach($this->attributes as $key => $value)  {

        	if(is_string($value))   {

            	$this->$key = trim($value);

        	}

    	}

    	return true;

	}


	public function beforeSave()

	{

    	// in this case, we will use the old hashed password.

    	if(empty($this->PASSWORD) && empty($this->REPEAT_PASSWORD) && !empty($this->INIT_PASSWORD)) {

        	$this->PASSWORD=$this->REPEAT_PASSWORD=$this->INIT_PASSWORD;

    	}   elseif(!empty($this->PASSWORD) && !empty($this->REPEAT_PASSWORD) && ($this->PASSWORD == $this->REPEAT_PASSWORD))   {

        	$this->PASSWORD = md5($this->PASSWORD);

        	$this->REPEAT_PASSWORD = md5($this->REPEAT_PASSWORD);

    	}


    	if($this->isNewRecord)  {

        	$this->CREATED_ON = time();

    	}   else	{

        	$this->UPDATED_ON = time();

    	}


    	return parent::beforeSave();

	}


	public function afterFind()

	{

    	//reset the password to null because we don't want the hash to be shown.

    	$this->INIT_PASSWORD = $this->PASSWORD;

    	$this->PASSWORD = null;

    	$this->assignee_name = $this->FIRST_NAME . ' ' . $this->LAST_NAME;


    	if(!Yii::app()->user->isGuest && (Yii::app()->user->user_type == 'admin' || Yii::app()->user->user_type == 'cro'))	{

        	if(!empty($this->hotel))	{

            	$this->assignee_name = $this->hotel->HOTEL_NAME . ' - '.$this->FIRST_NAME . ' ' . $this->LAST_NAME;

        	}

    	}


    	parent::afterFind();

	}





	/**

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

 	*

 	* Typical usecase:

 	* - Initialize the model fields with values from filter form.

 	* - Execute this method to get CActiveDataProvider instance which will filter

 	* models according to data in model fields.

 	* - Pass data provider to CGridView, CListView or any similar widget.

 	*

 	* @return CActiveDataProvider the data provider that can return the models

 	* based on the search/filter conditions.

 	*/

	public function search()

	{

		// @todo Please modify the following code to remove attributes that should not be searched.


		$criteria=new CDbCriteria;

    	$criteria->with = array('hotel');


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

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

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

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

		$criteria->compare($this->getTableAlias(false, false).'.HOTEL_ID',$this->HOTEL_ID);

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

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

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

//		$criteria->compare('CREATED_ON',$this->CREATED_ON);

//		$criteria->compare('UPDATED_ON',$this->UPDATED_ON);


    	$sort=new CSort;

    	$sort->defaultOrder = 'USER_ID DESC';

    	$sort->attributes=array(

        	'*',

        	'HOTEL_ID' => array( "asc"=>'hotel.HOTEL_NAME', "desc" => 'hotel.HOTEL_NAME desc')

    	);


    	return new CActiveDataProvider($this, array(

			'criteria'=>$criteria,

        	'sort'=>$sort

		));

	}


	/**

 	* Returns the static model of the specified AR class.

 	* Please note that you should have this exact method in all your CActiveRecord descendants!

 	* @param string $className active record class name.

 	* @return User the static model class

 	*/

	public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}

}



and action :


public function actionUpdate($id)

	{

		$model=$this->loadModel($id);


		// Uncomment the following line if AJAX validation is needed

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


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

		{

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

			if($model->save())

				$this->redirect(array('view','id'=>$model->USER_ID));

		}


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

			'model'=>$model,

		));

	}

And my form :


<div class="row">

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

    	<?php echo $form->passwordField($model, 'PASSWORD', array('size' => 40, 'maxlength' => 40, 'minlength' => 6)); ?>

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

	</div>

I can’t see any reason that what you’re doing wouldn’t work. Can you post the rest of your view?

This is update view


<?php

/* @var $this UserController */

/* @var $model User */


$this->breadcrumbs=array(

	'Users'=>array('index'),

	$model->USER_ID=>array('view','id'=>$model->USER_ID),

	'Update',

);


$this->menu=array(

	array('label'=>'List User', 'url'=>array('index')),

	array('label'=>'Create User', 'url'=>array('create'), 'visible' => (Yii::app()->user->user_type != 'sale' && Yii::app()->user->user_type != 'cro') ),

	array('label'=>'View User', 'url'=>array('view', 'id'=>$model->USER_ID)),

//	array('label'=>'Manage User', 'url'=>array('admin')),

);

?>


<h1>Update User <?php echo $model->USER_ID; ?></h1>


<?php $this->renderPartial('_form', array('model'=>$model)); ?>

and here is the form


<?php

/* @var $this UserController */

/* @var $model User */

/* @var $form CActiveForm */

?>


<div class="form">


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

    	'id' => 'user-form',

    	// Please note: When you enable ajax validation, make sure the corresponding

    	// controller action is handling ajax validation correctly.

    	// There is a call to performAjaxValidation() commented in generated controller code.

    	// See class documentation of CActiveForm for details on this.

    	'enableAjaxValidation' => false,

	)); ?>


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


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


	<div class="row">

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

    	<?php echo $form->textField($model, 'FIRST_NAME', array('size' => 50, 'maxlength' => 50)); ?>

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

	</div>


	<div class="row">

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

    	<?php echo $form->textField($model, 'LAST_NAME', array('size' => 50, 'maxlength' => 50)); ?>

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

	</div>


	<div class="row">

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

    	<?php echo $form->textField($model, 'EMAIL', array('size' => 50, 'maxlength' => 50)); ?>

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

	</div>


	<div class="row">

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

    	<?php echo $form->passwordField($model, 'PASSWORD', array('size' => 40, 'maxlength' => 40, 'minlength' => 6)); ?>

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

	</div>


	<div class="row">

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

    	<?php echo $form->passwordField($model, 'REPEAT_PASSWORD', array('size' => 40, 'maxlength' => 40, 'minlength' => 6)); ?>

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

	</div>


	<?php if(Yii::app()->user->user_type != 'sale' && Yii::app()->user->user_type != 'CRO'):	?>

	<div class="row">

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

    	<?php echo $form->dropDownList($model, 'USER_TYPE',

        	(Yii::app()->user->user_type == 'admin' || Yii::app()->user->user_type == 'cro')?

            	array('admin' => 'Admin', 'cro' => 'CRO', 'hotel'=>'Hotel', 'sale'=>'Sale'):array('hotel'=>'Hotel', 'sale'=>'Sale'),

        	array('empty' => 'Select')

    	); ?>

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

	</div>

	<?php endif ?>


	<div class="row">

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

    	<?php echo $form->dropDownList($model, 'HOTEL_ID',

        	CHtml::listData(

            	Hotel::model()->findAllByAttributes(array('HOTEL_STATUS' => 'E')),

            	'HOTEL_ID', 'HOTEL_NAME'

        	), array('empty' => 'Select')

    	); ?>

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

	</div>


	<div class="row">

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

    	<?php echo $form->dropDownList($model, 'USER_STATUS', array('E' => 'Enable', 'D' => 'Disable')); ?>

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

	</div>


	<div class="row buttons">

    	<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

	</div>


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


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

I can’t see why the password field would be populated on the initial page request, but if you’ve attempted to save the model and encountered an error, your beforeSave() method will repopulate the password with the hashed value.

Are you only seeing the field populated after a failed save?

Field is populated on initial update form, and I am not able to update the records because of the condition for repeat password validation.

And don’t know why, but field is populated only for 75% records. For 25% records, on initial update form, password field is blank (as expected).