Tricks

Show/Hide form field based on a boolean value with validation

Jan 3, 2023
Rezaul H Reza
Form builder, FAQ

If you want to show a field based on a boolean value for example:

Scenario:

Given a project has a Boolean column is_buyable and price. When project is buyable there must be a price assuming is_buyable is false by default. When it is buyable price cannot be empty.

Usually we would define the rules in a FormRequest or wherever suitable.

With Filament if we were to achieve something like that, all we have to do is:

  • Make the field reactive. In this case is_buyable.
  • Use the magic afterStateUpdated hook and define the first set of conditions here.
  • We can also add validation that it is required when price is not empty (though unnecessary because we cannot access the price field if it is not selected or switched on however you say so).
Toggle::make('is_premium')
->label('Premium?')
->reactive()
->requiredWith('price')
->afterStateUpdated(
fn ($state, callable $set) => $state ? $set('price', null) : $set('price', 'hidden')
),

Notice here we get set the state of the price field here. If is buyable is false then price field won’t be visible. If it is true we then set the price field initial value to null.

Then for the dependent field:

TextInput::make('price')
->label('Price (£)')
->requiredWith('is_premium')
->numeric()
->hidden(
fn (Closure $get): bool => $get('is_premium') == false
), //this is the trick.
 
// rest…

Bu default it is hidden. If buyable is selected it will show the price field. Let’s say you try to submit the form when it is selected and you leave the price field empty. It will throw a validation error. Because we are using requiredWith('is_buyable') , it will prevent the record being stored in the database.

Thanks a bunch. For more tips and tricks visit my website.