Courses

Filament 3 From Scratch: Practical Course

Dynamic Forms: Hidden, Disabled and "Reactive" Options

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Creating reactive form fields
- Auto-generating slugs
- Managing conditional fields
- Handling dynamic options

It seems like we know all about forms in Filament, but we actually just scratched the surface of possibilities in this course. The real power comes with the dynamic behavior of form fields. We will explore a few examples in this lesson.


Example 1. Auto-Generate Slug from Title

Suppose we have two DB fields: products.name and products.slug. And we want the slug to be auto-generated in the form as we're typing the name.

Typical Resource form:

app/Filament/Resources/ProductResource.php

return $form
->schema([
Forms\Components\TextInput::make('name')
->label(__('Product name'))
->required()
->unique(ignoreRecord: true),
Forms\Components\TextInput::make('slug')
->required(),

Now, how do we make this form reactive? We need to add two things to the "name" column:

  • Specify that it's ->live(), which means that the form is refreshed after its value change
  • Specify the afterStateUpdated() logic and what happens with that value

The code looks like this:

return $form
->schema([
Forms\Components\TextInput::make('name')
->label(__('Product name'))
->required()
->unique(ignoreRecord: true)
->live(onBlur: true)
->afterStateUpdated(fn (Forms\Set $set, ?string $state) => $set('slug', str()->slug($state))),
Forms\Components\TextInput::make('slug')
->required(),

So, the main action is in the callback function: we set the slug value to whatever we want from the initial $state variable value.

The important thing is a parameter in the live(onBlur: true). If you don't specify it, the form will auto-refresh while typing with every symbol, which is not a pleasant UX behavior, as it would keep overwriting the values. The onBlur would refresh the form only when you finish typing and click "Tab" or click away from the "name" input field.


Example 2. Disable Field in Edit Form

Let's continue our example of the slug field by making it disabled in the Edit form.

As usual, we need to add a method to the input chain. One of the possible methods is ->disabled(true/false). But the trick here is to add a condition as a parameter that should return true/false: WHEN it should be disabled.

Filament offers a better method called...

The full lesson is only for Premium Members.
Want to access all 24 lessons of this course? (101 min read)

You also get:

  • 76 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord