Dynamically Insert a field in an existing form at a given position.
1
Event::listen('backend.form.extendFieldsBefore', function ($widget) {
if (!$widget->getController() instanceof MyController || !$widget->model instanceof MyModel {
return;
}
$position = 4;
$before = $widget->fields;
$after = array_splice($before, $position-1);
$newFields = [
'myFirstField' => [
'type' => 'text',
'label' => 'My First Field',
],
'mySecondField' => [
'type' => 'switch',
'label' => 'My Second Field',
],
];
$widget->fields = array_merge($before, $newFields, $after);
});
Note: credit to @jaxwilko
You can add the following helper method in your plugin's boot method to make this easier:
\Backend\Widgets\Form::extend(function () {
$this->addDynamicMethod('insertFieldsAtPosition', function ($fields, $position) {
$after = array_splice($this->fields, $position-1);
$this->fields = array_merge($this->fields, $fields, $after);
});
}, true);
The example above would become:
Event::listen('backend.form.extendFieldsBefore', function ($widget) {
if (!$widget->getController() instanceof MyController || !$widget->model instanceof MyModel {
return;
}
$widget->insertFieldsAtPosition([
'myFirstField' => [
'type' => 'text',
'label' => 'My First Field',
],
'mySecondField' => [
'type' => 'switch',
'label' => 'My Second Field',
],
], position:4);
});
There are no comments yet
Be the first one to comment