FilamentF
Filament9mo ago
Ash

Right way to exclude specific enum options within ->options?

Say you have a column in your model casted as an Enum.

The enum class has getLabel, getColor, getIcon implemented.

Doing just the following in a forms select/togglebutton/etc component:

->options(enumClassWeMade::class)


Will render Labels, Icons, and Color. Great!

However, say I have 5 different cases, but a few of those cases are excluded from say a Select or Togglebutton form element due to tenancy reasons.

Previously creating and using a custom getOptionsArray was fine, I could exclude (except) it like this:

Select::make('enumExample')
                            ->label('Enum Example')
                            ->options(collect(enumClassWeMade::getOptionsArray())
                                ->except(enumClassWeMade::UNDEFINED->value)
                                ->toArray())
                            ->required(),


However this won't render the labels, icons, or colors as it returns an array.

Currently when say I want to exclude specific options - i do something like this:

ToggleButtons::make('enumExample')
    ->label('enumExample')
    ->options(fn () => collect(enumClassWeMade::cases())
        ->reject(fn ($case) => $case === enumClassWeMade::RANDOM_CASE_ONE)
        ->mapWithKeys(fn ($case) => [$case->value => $case->getLabel()])
        ->toArray()
    )
    ->icons(fn () => collect(enumClassWeMade::cases())
        ->reject(fn ($case) => $case === enumClassWeMade::RANDOM_CASE_ONE)
        ->mapWithKeys(fn ($case) => [$case->value => $case->getIcon()])
        ->toArray())
    ->colors(fn () => collect(enumClassWeMade::cases())
        ->reject(fn ($case) => $case === enumClassWeMade::RANDOM_CASE_ONE)
        ->mapWithKeys(fn ($case) => [$case->value => $case->getColor()])
        ->toArray())
    ->grouped()
    ->inline()
    ->required(),


This obviously excludes the right stuff and renders the proper icon and color too. I was wondering if there is a more elegant approach than the above?
Was this page helpful?