-
We're using states all over in our application. Thanks for making this! I have a question about displaying states in a dropdown (e.g. for filtering, or manually changing the state of a model). We're serialising states, so each state has a static How would I go about creating a dropdown where we can use I know about Any help would be greatly appreciated! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
There's no built-in support for generating that kind of data, since it's out of scope for this package. The way we solved it is by adding a It looks something like this: /**
* @param string|\Spatie\ModelStates\State|array|\Illuminate\Support\Collection $stateOptions
*
*/
protected function stateOptions($stateOptions, Model $model): array
{
if (is_subclass_of($stateOptions, State::class)) {
$stateOptions = $stateOptions::all();
}
if (is_array($stateOptions)) {
$stateOptions = collect($stateOptions);
}
return $this->options($stateOptions->mapWithKeys(function (string $className) use ($model) {
/**
* @var \Spatie\ModelStates\State
* @var \Spatie\ModelStates\State $state
*/
$state = new $className($model);
$label = method_exists($state, 'label')
? $state->label()
: $state::getMorphClass();
return [$className::getMorphClass() => $label];
}));
} If you don't have a concrete model at hand, we'd simply pass |
Beta Was this translation helpful? Give feedback.
There's no built-in support for generating that kind of data, since it's out of scope for this package.
The way we solved it is by adding a
stateOptions(string $stateClass): array
method on a base view model class in our projects. If you're not using view models you could write such a function somewhere else so that it's reusable.It looks something like this: