FilamentPHP: Showing/Hiding Form Components based on Toggle

Published on April 29, 2024. Last updated on January 22, 2025.
FilamentPHP: Showing/Hiding Form Components based on Toggle

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: