DEV Community

Cover image for Update/add field to modal when use createOptionForm in Laravel Filament 3

Posted on

Update/add field to modal when use createOptionForm in Laravel Filament 3

When you use modal window to create a model relations without leaving the main model creation page, it is convenient. However, sometimes you need to add or update the fields that the user fills in the modal window. This is not described in the documentation but it is quite easy to do. For example, let's add a slug for a category.

To do this, we need to call createOptionAction to which we pass a callback in which we will process $action. In this action, you need to call the mutateFormDataUsing method in which we can process the $data in another callback. Not such a callback hell as in js, but it is already starting to be alarming 😅

use Filament\Forms\Components\Actions\Action;
use Filament\Forms;
use Filament\Forms\Form;
use Illuminate\Support\Str;

public static function form(Form $form): Form

    return $form
                ->relationship('categories', 'title')
                ])->createOptionAction(function (Action $action) {
                    $action->mutateFormDataUsing(function (array $data) {
                        $data['slug'] = Str::slug($data['title']);

                        return $data;
Enter fullscreen mode Exit fullscreen mode

In general, this action is almost no different from the create action that is already described in the documentation

Top comments (1)

altomar profile image
Pedro Altomar

Nice post! Any idea on how to pre-fill some of the fields in the option form modal when you're reusing the original resource's form? like:
->createOptionForm(fn (Form $form) => AccountResource::form($form))
because ->mutateFormDataUsing() is just for modifying them before saving, right?