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 have a scenario where I'm adding a switch field to the Backend\Controllers\Users form. The field is there to trigger something else to be created in the system when a new Backend/Models/User is created.
Within the boot
method of my plugin:
Event::listen('backend.form.extendFields', function($widget) {
if ( ! $widget->getController() instanceof Backend\Controllers\Users) return;
if ( ! $widget->model instanceof Backend\Models\User) return;
// move superuser to left side
$permissionField = $widget->getField('permissions[superuser]');
$permissionField->span = 'left';
// add switch for employee creation
$widget->addFields([
'create_employee' => [
'label' => 'Create Employee',
'comment' => 'When creating an account, also make an employee.',
'type' => 'switch',
'default' => 1,
'span' => 'right',
]
]);
});
The field is added to the form and everything is good but when I try to save it, it's throwing an error around the create_employee
column not being found.
I see that the Purgeable trait is something that already exists on User parent model. The purgeable
property is protected though and when I extend the User model in an attempt to set another purged value, it throws an error.
User::extend(function($model) {
$model->purgeable[] = 'create_employee';
$model->bindEvent('model.afterCreate', function() use($model) {
if($model->getOriginalPurgeValue('create_employee') == 1) {
$employee = new Employee;
$employee->user()->associate($model);
$employee->save();
}
});
});
Is there a way to extend the purgeable array from outside the class? Should I be thinking about this differently?
Figured it out. Instead of directly trying to set the property, the trait has a method to purgeAttributes
.
So replace:
$model->purgeable[] = 'create_employee';
With:
$model->bindEvent('model.saveInternal', function() use($model) {
$model->purgeAttributes('create_employee');
});
Last updated
1-2 of 2