Reputation: 205
I did CRUD in Yii2 Advanced- backend. I used class extend ActiveRecord. And I have a problem with the password attribute, when I want to update it displays the hashed password with a lot of dots, when I try to update it doesn't save the hashed password. So I used beforeSave to hash my password:
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if($this->isNewRecord) {
$this->created_at = time();
$this->status = self::DEFAULT_STATUS;
$this->generateAuthKey();
$this->setPassword($this->PasswordHash);
$this->RulesAccept=1;
return true;
} else {
$this->setPassword($this->PasswordHash);
return true;
}
}
}
I dont know how can I do that when I displayed the updating form it display me dots from hashed password and if you do not change the password also will not change. Currently, and each time you click Update my password is changed or re-hashing. How can I avoid this. I trying to use empty value in form like this:
<label class="control-label"> <?= Yii::t('app', 'Hasło')?> </label>
<?= $form->field($model, 'PasswordHash')->passwordInput(['placeholder' => Yii::t('app', 'Utwórz hasło'), 'value' => ''])->label('') ?>
And then i tried to check in my beforeSave() if input form was empty then does not save this password just leave it as it is in the database:
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if($this->isNewRecord) {
$this->created_at = time();
$this->status = self::DEFAULT_STATUS;
$this->generateAuthKey();
$this->setPassword($this->PasswordHash);
$this->RulesAccept = 1;
return true;
} else {
if((!empty)$this->PasswordHash)){
$this->setPassword($this->PasswordHash);
return true;
}
return false;
}
}
}
So always when i come in the form of update i see empty input of password. And if i dont wrote new passwort it change only all attributes which i changed, but if i wrote some password it save me this new password. I think this function should work that but i wrong and this form always change password. What can i do to fix that. Maybe there is some other way?
Upvotes: 0
Views: 437
Reputation: 31
you can use $this->isAttributeChanged('password_field')
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if ($this->isAttributeChanged('PasswordHash')) {
$this->setPassword($this->PasswordHash);
}
return true;
} else {
return false;
}
}
Upvotes: 1