Disable Form Inputs Dynamically Based on Other Fields

2024-10-10

If you want to disable some form inputs based on the values of other fields like checkbox/select, this tutorial will help you.

This tutorial is based on the question we received on YouTube:

Let's look at a typical example of billing/shipping addresses when placing an order in an e-shop.

Shipping address details should be filled in only if they differ from the billing address, right?

For that, we will have a checkbox labeled "Same as billing", with the default checked and inputs disabled.

When that checkbox is unchecked, the three fields below will become active, and you can fill them in.

In the code, you need to have two things:

  1. ->live() on the checkbox
  2. ->disabled() with the condition on the inputs or, in our case, input group
return $form
->schema([
Forms\Components\Section::make('Billing Details')
->columnSpan(1)
->schema([
Forms\Components\TextInput::make('billing_address')
->label('Address')
->required(),
Forms\Components\TextInput::make('billing_postcode')
->label('Postcode')
->required(),
Forms\Components\TextInput::make('billing_city')
->label('City')
->required(),
]),
Forms\Components\Section::make('Shipping Details')
->columnSpan(1)
->schema([
Forms\Components\Checkbox::make('use_billing_address')
->live()
->default(true)
->label('Same as billing'),
Forms\Components\Group::make([
Forms\Components\TextInput::make('shipping_address')
->label('Shipping Address'),
Forms\Components\TextInput::make('shipping_postcode')
->label('Shipping Postcode'),
Forms\Components\TextInput::make('shipping_city')
->label('Shipping City'),
])->disabled(fn (Forms\Get $get) => $get('use_billing_address'))
])
]);

The value $get('use_billing_address') will return TRUE or FALSE, depending on whether that checkbox is checked.

Another good thing is that when inputs are disabled, they will NOT come through the request to be saved into the database. So, no additional validation is needed.

A few of our Premium Examples: