Advanced
Using closure customization
All configuration methods for fields and layout components accept closures as parameters instead of hardcoded values:
use App\Models\User;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
DatePicker::make('date_of_birth')
->displayFormat(function () {
if (auth()->user()->country_id === 'us') {
return 'm/d/Y'
} else {
return 'd/m/Y'
}
})
Select::make('userId')
->options(function () {
return User::all()->pluck('name', 'id');
})
TextInput::make('middle_name')
->required(function () {
return auth()->user()->hasMiddleName();
})
This alone unlocks many customization possibilities.
The package is also able to inject many utilities to use inside these closures, as parameters.
If you wish to access the current state (value) of the component, define a $state parameter:
function ($state) {
// ...
}
If you wish to access the current component instance, define a $component parameter:
use Filament\Forms\Components\Component;
function (Component $component) {
// ...
}
If you wish to access the current Livewire component instance, define a $livewire parameter:
use Livewire\Component as Livewire;
function (Livewire $livewire) {
// ...
}
If you have defined a form or component Eloquent model instance, define a $record parameter:
use Illuminate\Database\Eloquent\Model;
function (?Model $record) {
// ...
}
You may also retrieve the value of another field from within a callback, using a closure $get parameter:
use Closure;
function (Closure $get) {
$email = $get('email'); // Store the value of the `email` field in the `$email` variable.
//...
}
In a similar way to $get, you may also set the value of another field from within a callback, using a closure $set parameter:
use Closure;
function (Closure $set) {
$set('title', 'Blog Post'); // Set the `title` field to `Blog Post`.
//...
}
If you're writing a form for an admin panel resource or relation manager, and you wish to check if a form is create, edit or view, use the $context parameter:
function (string $context) {
// ...
}
Outside of the admin panel, you can set a form's context by defining a
getFormContext()method on your Livewire component.
Callbacks are evaluated using Laravel's app()->call() under the hood, so you are able to combine multiple parameters in any order:
use Closure;
use Livewire\Component as Livewire;
function (Livewire $livewire, Closure $get, Closure $set) {
// ...
}
Reloading the form when a field is updated
By default, forms are only reloaded when they are validated or submitted. You may allow a form to be reloaded when a field is changed, by using the reactive() method on that field:
use Filament\Forms\Components\TextInput;
TextInput::make('title')->reactive()
A great example to give a use case for this is when you wish to generate a slug from a title field automatically: