I have a user form that asks for password confirmation. In Yii 1.1 I used to do the following:
User model:
public $clrTxtPwd;
public $clrTxtPwdConfirm;
public function rules()
{
...
array('clrTxtPwdConfirm', 'compare', 'compareAttribute'=>'clrTxtPwd', 'allowEmpty'=>true, 'on'=>'update', 'message'=>Yii::t('app','Passwords do not match, try again.')),
}
public function beforeSave()
{
if ($this->isNewRecord) {
$this->h_password = CPasswordHelper::hashPassword($this->clrTxtPwd);
}
else { // update only changed attributes
if(!empty($this->clrTxtPwd)) {
$this->h_password = CPasswordHelper::hashPassword($this->clrTxtPwd);
}
}
return parent::beforeSave();
}
Now using Yii2 I’ve tried the following:
User model:
public $clrTxtPwd;
public $clrTxtPwdConfirm;
public function rules()
{
...
[['clrTxtPwd','clrTxtPwdConfirm'], 'compare', 'skipOnEmpty'=>true, 'on'=>'update'],
}
public function setPassword($password)
{
$this->password_hash = Yii::$app->getSecurity()->generatePasswordHash($password);
}
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if (!empty($this->clrTxtPwd)) {
$this->setPassword($this->clrTxtPwd);
}
return true;
}
else {
return false;
}
}
but it’s not changing the password. The log shows that it failed to set the unsafe attributes $clrTxtPwd and $clrTxtPwdConfirm.
I’m kind of lost here; any help is greatly appreciated.
Thanks,