lpoolerl
(Rt Vitalmax)
1
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:
-
leave password fields empty on EVERY user update page.
-
"ON SUBMIT - user update page" - if password is EMPTY - do not change his password
-
"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 = '';
parent::afterFind();
}
And in my action:
$model->attributes=$_POST['MyUserModel'];
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.
Ankit_Modi
(Ankit Modi)
2
Also you can use the beforsave methods
like
public function beforeSave()
{
$pass = md5($this->password);
$this->password = $pass;
return true;
}
lpoolerl
(Rt Vitalmax)
3
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
Ankit_Modi
(Ankit Modi)
4
means if I am not change the password field so old password is saved DB?
Ankit_Modi
(Ankit Modi)
6
ok you can set the rules function
array('password', 'required', 'on' => 'create'),
array('password','required','allowEmpty' => TRUE, 'on' => 'update'),
n4shru1
(N4shru1)
7
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)
n4shru1
(N4shru1)
9
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. 