This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.
I'm writing a plugin that adds a hashable field (think password field) to the backend user model - let's call it pass2. Problem is, when I submit the backend user form with pass2 field blank, the DB contents are emptied rather than ignored the way the password field is.
The issue is pretty easy to understand. The \October\Rain\Auth\Models\User.php model contains the following:
/**
* Protects the password from being reset to null.
*/
public function setPasswordAttribute($value)
{
if ($this->exists && empty($value)) {
unset($this->attributes['password']);
}
else {
$this->attributes['password'] = $value;
// Password has changed, log out all users
$this->attributes['persist_code'] = null;
}
}
As you can see, password field is cleared if it's empty. Unfortunately because I'm extending the model with a plugin, I don't have the luxury of writing a setPass2Attribute() method and instead need to rely on the model.beforeSetAttribute and model.setAttribute events however the latter runs too late and the former actively ignores you trying to unset the field by nulling it:
// Before Event
if (($_value = $this->fireEvent('model.beforeSetAttribute', [$key, $value], true)) !== null)
$value = $_value;
So... how do I unset the pass2 field with a plugin on form submit if it's empty?
Last updated
This solves my problem:
$model->bindEvent('model.setAttribute', function($key, $value) use ($model) {
if ( $key == 'pass2' && $value === '' )
unset($model->attributes[$key]);
});
Flynsarmy said:
This solves my problem:
$model->bindEvent('model.setAttribute', function($key, $value) use ($model) { if ( $key == 'pass2' && $value === '' ) unset($model->attributes[$key]); });
Saved my day!
1-3 of 3