Not saving particular data in a model

Hello everyone

In my model (User), I have a field called password. When I create a user, I provide a password and save the MD5 version into Database.

There are two problems:

  1. When I want to update a user, the password field shows the MD5 version of the stored password

  2. When I want to update a field i.e. First Name, it also shows the password field filled with the MD5 version of the password. That’s because in update form the password field is filled with whatever is in DB and of course MD5’ed version of the password is in DB.

Instead I want to have the password field blank which means NO update on password BUT if I provide a password, it has to Save the MD5 of that.

I tried to have to different _form.php for update which does not show the password field but it is just hidden and still there with MD5 password

Any hint guys?

In your form, before printing the password field, insert a line:


$model->password = '';

Add to your model:


    public function  beforeValidate()

    {

        if (isset($this->password) && $this->password === '' && $this->scenario === 'update') {

            unset($this->password);

        }

        return parent::beforeValidate();

    }



I strongly suggest you use a tested authentification system instead of your own method. See "Encrypting passwords" in How to write secure Yii applications.

With the code you provided, it does not show the password so the first part is working but the beforeValidate(), in User.php, does not work.I left the password field blank but it still gets the encrypted password and encrypts it then saves it into DB !!!!

thanks François Gannaz

your code did exactly what I needed

@Liz: are you encrypting the password in beforeSave() ?

if so you might need to add: if(!empty($this->password))

I dont why but it does not save anything if I use beforeSave() The only place I can actually encrypt and save the password is afterValidate(). Really dont know why beforeSave() does not eork

Thank everyone

All I had to do was





public function  beforeValidate()

    {

        if (empty($this->password) && isset($this->password)) {

            unset($this->password);

            

        }

        else

        {$this->password=MD5($this->password);

		}

        

        return parent::beforeValidate();

    }



It does not look right but it does the job.