FilamentF
Filament2y ago
Imam

How to make dynamic range Options Select Form Based on Selected State

Hello, this is my first question, and I appreciate your assistance.
I have a select input to provide information about the number of children someone has. The options in this select range from 0 to a maximum of 20, obtained using array_combine.

Here's my code :
use Filament\Forms\Components\Component as FormComponent;

Select::make('children_information_number')
->hiddenLabel()
->columnSpan('4')
->selectablePlaceholder(false)
->live()
->options(array_combine(range(0, 20), range(0, 20)))
->afterStateUpdated(function ($state, FormComponent $component) {
    if ($state > 0) {
        $options = array_combine(range($state, 20), range($state, 20));
        $component->options($options);
    }
})


I want to make the range in these options dynamic by utilizing afterStateUpdate(), where the initial range is determined based on the $state chosen by the user.
The code I created successfully achieves this, but after a while, the values in the options change unexpectedly.

For example condition:
  1. The select option initially contains numbers from 0 to 20.
  2. When a user selects the number 3, the select options should change to display numbers from 3 to 20.
  3. However, the issue I'm experiencing is that, for a brief moment, the selected number 3 changes to 6, as if there is a glitch that temporarily alters the $state to 6.
  4. I have already added debounce to live(), but it doesn't seem to resolve the issue. Can anyone help me fix this problem?
Thank you
Screenshot_2024-01-22_at_17.54.19.png
Screenshot_2024-01-22_at_17.54.46.png
Solution
You need to use the Filament setters.

->afterStateUpdated(function ($state, FormComponent $component, $set) {
    if ($state > 0) {
        $options = array_combine(range($state, 20), range($state, 20));
        $component->options($options);
        // Setter
        $set('my_select', $options);
    }
})
Was this page helpful?