Tricks

Reusing Forms when using Tables and Forms

Feb 14, 2023
Tony Partridge
Table builder, Form builder

When using Filament Admin, there is a schema function which reuses the form for both, edit and create. However, in the forms implementation this is not the case and as such you need to write your own function to handle it. Here we will go through a baseline example of how this can be achieved.

Firstly create a new function which your schema:

public function inputForm(): array {
return [
TextInput::make('name'),
TextInput::make('email')->email()
};
}

Now we have the schema we need to include it in the $form with the following example:

$form->schema($this->inputForm())

As such your form will now render your form as expected.

However, say you want the form to be used on a edit method on the same page in an action, or any other action on the table you just call the form the same way.

As an example with the Filament Table you can do:

return $table
->columns([
TextColumn::make('id')
->label('Id')
->hidden(),
TextColumn::make('name')
->label('Name')
->action(
Action::make('edit')
->label('Edit')
->visible(auth()->user()->can('edit'))
->mountUsing(fn (Forms\ComponentContainer $form, Model $record) => $form->fill($record->toArray()))
->form($this->inputForm())
->action(fn (Model $record, array $data): => $record->update($data))),
)
->toggleable()
->sortable(),
]),
TextColumn::make('email')
->label('Email Address')
->toggleable()
->sortable(),
]);

This should help give you a basic example of how to re-use a form within a implementation outside of Filament Resources.

Note: In the example above we are also using sortable() and toggleable() which will show sortable headers on the rows, and an icon for toggling on and off columns where toggleable() is in use. Finally, ensure you replace out Model with your ModelName i.e. 'User'.

No comments yet…