Filtering Enum Options
How would one filter enum options? I don't want to include all enum options; only a subset.
This gives an exception:
Filament\Forms\Components\ToggleButtons::isOptionDisabled(): Argument #2 ($label) must be of type string, App\Enums\Party given
I've seen seen the option, disableOptionWhen
, but I don't want to disable the option, I want to hide it entirely from view.
Additionally, I can always do a rigmarole of collection(..enum)->filter
within options
but that will eliminate icons, colors, and labels defined in the enum.5 Replies
1 . If your enum implements cases(), you can filter and map easily:
php
Copy
Edit
->options(
collect(Party::cases())
->filter(fn($case) => in_array($case, [Party::OWNER, Party::TENANT]))
->mapWithKeys(fn($case) => [$case->value => $case->label()])
->toArray()
)
Of course, you'll need a label() method on your enum like:
php
Copy
Edit
enum Party: string
{
case OWNER = 'owner';
case TENANT = 'tenant';
case GUEST = 'guest';
public function label(): string { return match($this) { self::OWNER => 'Owner', self::TENANT => 'Tenant', self::GUEST => 'Guest', }; } } 2. You can create a method like: php Copy Edit public static function filteredOptions(array $allowed): array { return collect(self::cases()) ->filter(fn($case) => in_array($case, $allowed)) ->mapWithKeys(fn($case) => [$case->value => $case->label()]) ->toArray(); } Then in Filament: php Copy Edit ->options( Party::filteredOptions([Party::OWNER, Party::TENANT]) )
public function label(): string { return match($this) { self::OWNER => 'Owner', self::TENANT => 'Tenant', self::GUEST => 'Guest', }; } } 2. You can create a method like: php Copy Edit public static function filteredOptions(array $allowed): array { return collect(self::cases()) ->filter(fn($case) => in_array($case, $allowed)) ->mapWithKeys(fn($case) => [$case->value => $case->label()]) ->toArray(); } Then in Filament: php Copy Edit ->options( Party::filteredOptions([Party::OWNER, Party::TENANT]) )
Thanks, doesn't that get messy with defined colors and icons, essentially have do something like
->icons(..)
, ->colors(...)
with a similar pattern?yes, you’ve identified a very real pain point when using enums + Filament components that expect options, colors, icons, etc.
Would be a nice PR 😉
Sound great