Clear Related Field in Repeater Form

2024-06-07

When dealing with invoices or orders - we usually have a Quantity field next to a Product field. To provide a better user experience, we should clear a related field once the parent value changes. We don't want to see our users order too much of a different thing, do we?

In our case, we have an Order creation form. This form has a repeater field for products and a quantity field.

Forms\Components\Repeater::make('products')
->columnSpan(2)
->columns()
->schema([
Forms\Components\Select::make('product_id')
->options(Product::pluck('name', 'id')->toArray())
->disableOptionsWhenSelectedInSiblingRepeaterItems()
Forms\Components\TextInput::make('quantity'),
]),

But this brings us a challenge - what if someone had 1000 stickers selected and then changed their mind about the product and accidentally selected 1000 notebooks? This is something we can prevent by simply resetting the quantity field when the product is changed:

Forms\Components\Repeater::make('products')
->columnSpan(2)
->columns()
->schema([
Forms\Components\Select::make('product_id')
->options(Product::pluck('name', 'id')->toArray())
->disableOptionsWhenSelectedInSiblingRepeaterItems()
->live()
->afterStateUpdated(function (Forms\Set $set) {
$set('quantity', null);
}),
Forms\Components\TextInput::make('quantity'),
]),

Just two lines of code and our users have a much better experience.

A few of our Premium Examples: