If Password Field Is Empty - Don't Change It

Hey everyone!

I have a "user" table in DB.

There is a field "password" - it stores HASHED password.

I have a model "User".

I have a CRUD pages on my site (admin part of my site) to manage this table’s data.

By default - hashed password will be set as a value on update user page.

I want to:

  1. leave password fields empty on EVERY user update page.

  2. "ON SUBMIT - user update page" - if password is EMPTY - do not change his password

  3. "ON SUBMIT - user update page" - if a password is not EMPTY - hash it and save to DB.

Ok, a bit of code:

1st “wish” :)

public function afterFind()



        * We store hashed password in DB so we should

        * NEVER display it


        $this->password = '';



And in my action:


But if a password is EMPTY - it (empty one) will be saved to DB.

Should I redefine "setAttributes" method? But how?

Any help will be appreciated.

Thanks in advance.

Also you can use the beforsave methods


 public function beforeSave()


        $pass = md5($this->password);

        $this->password = $pass;

        return true;


Yep, thank you!

I have "beforeSave":

public function beforeSave()


        if(parent::beforeSave()) {

            $password = password_hash($this->password, PASSWORD_DEFAULT);

            $this->password = $password;

            return true;


        return false;


But if you type empty password - it will be hashed and saved to DB

means if I am not change the password field so old password is saved DB?


Let me correct a bit:

ok you can set the rules function

 array('password', 'required', 'on' => 'create'),

 array('password','required','allowEmpty' => TRUE, 'on' => 'update'),

In Yii 1.14

I got problem message : "Property "CRequiredValidator.allowEmpty" is not defined."

I try to not to show password field (data from DB), but the password still saved & encrypted. How to not change the password??

Anyone Please help me. :(

There’s no such a thing as “required” + “can be empty” (this doesn’t make sense), that’s why RequiredValidator has no allowEmpty option.

What you want is to create virtual model attribute, for example,

public $new_password = '';

and create input field for ‘new_password’ the same way as you do for db attribute fields.

Then in beforeSave you check $this->new_password and either assign hashed value to $this->password or do nothing.

Don’t forget to add $new_password to validation rules if you plan to use mass-assignment on it (it can be just ‘safe’ validation rule)

First, ty for reply.

I got the answer.

I just make a variable than check with the password:

if($this->originalAttribute('password') != $this->password) 


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


I hope this help someone. :)