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
->schema([
Forms\Components\Select::make('categories')
->relationship('categories', 'title')
->multiple()
->searchable()
->preload()
->createOptionForm([
Forms\Components\TextInput::make('title')
->required()
->maxLength(255),
])->createOptionAction(function (Action $action) {
$action->mutateFormDataUsing(function (array $data) {
$data['slug'] = Str::slug($data['title']);
return $data;
});
})
]);
}
In general, this action is almost no different from the create action that is already described in the documentation
Top comments (2)
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?I think I'm a little late with the answer 🙃, but maybe it will be useful to someone in the future. You can use the default method to insert a value for the new form. Something like this:
->createOptionForm([
Forms\Components\TextInput::make('title')
->required()
->default('Some pre-fill title')
->maxLength(255),
])