Winter CMS resources and help articles

Simple and to the point. Optimized by the community.

Dynamically Insert a field in an existing form at a given position.

1
by mjauvin, last modified on September 6th, 2024
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); 
});

Discussion

0 comments

We use cookies to measure the performance of this website. Do you want to accept these cookies?