Here is an example of how to create a custom form field in Filament:
Creating a Custom Slug Form Field
1. Create a new Filament component in `app/Filament/Forms/Components/Slug.php`:
php
namespace App\Filament\Forms\Components;
use Filament\Forms\Components\Field;
class Slug extends Field
{
protected string $view = 'filament.forms.components.slug';
public function getStateBindingAttribute(): ?string
{
return 'slug';
}
public function getSuffixView(): ?string
{
return 'filament.forms.components.slug-suffix';
}
}
2. Create the view for the Slug component in `resources/views/filament/forms/components/slug.blade.php`:
html
<x-dynamic-component
:component="$getFieldWrapperView()"
:id="$getId()"
:label="$getLabel()"
:helper-text="$getHelperText()"
:hint="$getHint()"
:required="$isRequired()"
:state-path="$getStatePath()"
>
<div class="flex items-center space-x-2">
<div class="flex-1">
<x-filament-support::input
:id="$getId()"
:name="$getName()"
:value="$getState()"
:placeholder="$getPlaceholder()"
:disabled="$isDisabled()"
:required="$isRequired()"
wire:model.defer="{{$getStatePath()}}"
type="text"
class="block w-full transition duration-75 rounded-lg shadow-sm focus:border-primary-500 focus:ring-1 focus:ring-inset focus:ring-primary-500 disabled:opacity-70"
/>
</div>
<div>
@if($getSuffixView())
<x-dynamic-component :component="$getSuffixView()" />
@endif
</div>
</div>
</x-dynamic-component>
3. Create the view for the Slug suffix in `resources/views/filament/forms/components/slug-suffix.blade.php`:
html
<span class="text-gray-500">
{{ config('app.url') }}/
</span>
4. Now you can use the custom Slug field in your Filament resource forms:
php
use App\Filament\Forms\Components\Slug;
public static function form(Form $form): Form
{
return $form
->schema([
TextInput::make('title')
->required()
->maxLength(255),
Slug::make('slug')
->required()
->columnSpan([
'default' => 2,
'sm' => 1,
]),
RichEditor::make('content')
->required(),
]);
}
In this example, we've created a custom Slug form field that includes a prefix (the application URL) and automatically generates the slug based on the title. The Slug field is then used in the resource form schema.
The key steps are:
1. Create a new Filament component that extends the `Field` class and defines the view.
2. Create the Blade view for the Slug component, which includes the input field and the suffix.
3. Create an optional suffix view for the Slug component.
4. Use the custom Slug field in the resource form schema.
This allows you to easily add custom form fields to your Filament admin panels without having to write a lot of boilerplate code.
Citations:[1] https://laracasts.com/discuss/channels/filament/custom-form-in-filament-after-the-original-form?reply=916891
[2] https://dev.to/snehalkadwe/filament-v3-with-laravel-10-3h9k
[3] https://www.youtube.com/watch?v=SXZQhA9SqJQ
[4] https://redberry.international/laravel-filament-create-admin-panel/
[5] https://www.youtube.com/watch?v=6c4jVLWmDYU