F
Filament2mo ago
Neamix

Dynamic Filter

I want to create dynamic filter like step filter example i have table pet and each pet have type and each type contain a group of species so what i want to do here to allow user to choose the type first then the species appear to him i tried that concept
->filters([
SelectFilter::make('pet_type_id')
->label('نوع الحيوان')
->query(fn($data) => Session::put('pet.pet_type_id',$data['value'] ?? null))
->options(PetType::pluck('name_ar','id')->toArray()),

SelectFilter::make('pet_specie_id')
->options(function() {
$selectedPetType = Session::get('pet.pet_type_id');
dump($selectedPetType);
if ($selectedPetType)
return PetSpecie::where('pet_type_id',$selectedPetType)->pluck('specie_ar','id')->toArray();
else
return PetSpecie::pluck('specie_ar','id')->toArray();
})
->label('فصيلة الحيوان'),

SelectFilter::make('pet_color_id')
->label('لون الحيوان')
->options(PetColor::pluck('color_ar', 'id')->toArray()),
])
->filters([
SelectFilter::make('pet_type_id')
->label('نوع الحيوان')
->query(fn($data) => Session::put('pet.pet_type_id',$data['value'] ?? null))
->options(PetType::pluck('name_ar','id')->toArray()),

SelectFilter::make('pet_specie_id')
->options(function() {
$selectedPetType = Session::get('pet.pet_type_id');
dump($selectedPetType);
if ($selectedPetType)
return PetSpecie::where('pet_type_id',$selectedPetType)->pluck('specie_ar','id')->toArray();
else
return PetSpecie::pluck('specie_ar','id')->toArray();
})
->label('فصيلة الحيوان'),

SelectFilter::make('pet_color_id')
->label('لون الحيوان')
->options(PetColor::pluck('color_ar', 'id')->toArray()),
])
the only reason that i used query() because it was the only thing that worked as a callback function and this approche worked but the problem is that he get the prev type as example if i have type 0 default ,1 ,2 if i changed type from 0 to 1 it will show species of 0 if i changed 1 to 2 it will show species of 1 and so one
1 Reply
403gtfo
403gtfo2mo ago
I've done some similar stuff. You can use a combination of Get, hidden(), live(), and a function in your options() Get - Gets another field's value live() - lets the field update after load hidden() - Use a function with some logic on pet_specie_id that uses Get to check pet_type_id. If pet_type_id is not set hide pet_specie_id options() - again, use a function with logic in pet_specie_id that Gets pet_type_id and pulls the right option array. There is probably a nicer way, but hope this puts you on the right path. Also side note: if you add swift after the three backticks in your code block it will color code stuff like this:
Test::make('this')->live();
// Cool huh
Test::make('this')->live();
// Cool huh
Link to doco: https://filamentphp.com/docs/3.x/forms/advanced#injecting-the-state-of-another-field
Want results from more Discord servers?
Add your server