FilamentF
Filament9mo ago
Batman

Populate Select with only a select subset of an enum

What I am trying to achieve is populating the Select with only certain values of an Enum based on permissions. It is likely I am approaching this entirely the wrong way, and have tried various solutions without success.

Although this does not work, it shows what I am trying to achieve. The ArticleStatus is a backed Enum and the value of that enum is stored in the status attribute (it is casted).
Everything works properly if I want to load all the values of the enum (->options(ArticleStatus::class)).

Running the code below gives this error: Filament\Forms\Components\Select::isOptionDisabled(): Argument #2 ($label) must be of type string, App\Enums\ArticleStatus given

Select::make('status')
  ->selectablePlaceholder(false)
  ->options(fn (?Article $record, $operation) => Article::getStatusSelectBuilder($record, $operation))
  ->getOptionLabelUsing(fn ($value): ?string => ArticleStatus::from($value)->getLabel())
  ->required(),
Solution
So you could map the allowed enum cases to key/value pairs (enum value as key, and label as value) for ->options/icons/colors:

Select::make('status')
    ->selectablePlaceholder(false)
    ->options(fn (?Article $record, $operation) => 
        collect(Article::getStatusSelectBuilder($record, $operation))
            ->mapWithKeys(fn($status) => [$status->value => $status->getLabel()])
            ->toArray()
    )
    ->icons(fn (?Article $record, $operation) =>
        collect(Article::getStatusSelectBuilder($record, $operation))
            ->mapWithKeys(fn($status) => [$status->value => $status->getIcon()])
            ->toArray()
    )
    ->colors(fn (?Article $record, $operation) =>
        collect(Article::getStatusSelectBuilder($record, $operation))
            ->mapWithKeys(fn($status) => [$status->value => $status->getColor()])
            ->toArray()
    )
    ->default(ArticleStatus::DRAFT->value)
    ->required();


Just doesn't seem too DRY for my liking, unless you make some sort of macro, or some helper. Gonna eventually dive into options() to improve this but gotta move on to the next feature now lol.
Was this page helpful?