FilamentPHP: Showing/Hiding Form Components based on Toggle

Learn how to create dynamic forms in FilamentPHP by showing or hiding form components based on toggle actions.

FilamentPHP: Showing/Hiding Form Components based on Toggle

April 29, 2024

In this article, we will demonstrate how to dynamically show/hide form components based on the state of a toggle component.

 

Begin by adding a Toggle Component:

Forms\Components\Toggle::make('schedule')
    ->default(false)
    ->live(),

The live() method is the important part. Without adding it to the Toggle component, the page will update its state only when the form is submitted.

In this example, we'll use a Section Component with a Date Picker to illustrate the concept:

Forms\Components\Section::make('Schedule Info')
->schema([
    Forms\Components\DateTimePicker::make('published_at')
])

To conditionally display it based on the Toggle Component, we'll utilize the visible() method with a callback:

Forms\Components\Section::make('Schedule Info')
->visible(fn(Forms\Get $get) => $get('schedule'))
->schema([
    Forms\Components\DateTimePicker::make('published_at'),
])

The final output will look like this: