diff --git a/src/Components/Inputs/Select.php b/src/Components/Inputs/Select.php index aad44f0..1808656 100644 --- a/src/Components/Inputs/Select.php +++ b/src/Components/Inputs/Select.php @@ -2,7 +2,7 @@ namespace Rawilk\FormComponents\Components\Inputs; -use function config; +use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Arr; use Illuminate\Support\Collection; use Illuminate\Support\HtmlString; @@ -62,18 +62,7 @@ public function __construct( $this->disabledField = $disabledField ?? config('form-components.defaults.global.disabled_field', 'disabled'); $this->childrenField = $childrenField ?? config('form-components.defaults.global.children_field', 'children'); - $this->options = collect($options) - ->map(function ($value, $key) { - // If the key is not numeric, we're going to assume this is the value. - if (! is_numeric($key)) { - return [ - $this->valueField => $key, - $this->labelField => $value, - ]; - } - - return $value; - })->values(); + $this->options = $this->normalizeOptions($options); } /** @@ -99,4 +88,28 @@ public function inputClass(): string 'input-error' => $this->hasErrorsAndShow($this->name), ]); } + + protected function normalizeOptions(array|Collection $options): Collection + { + return collect($options) + ->map(function ($value, $key) { + // If the key is not numeric, we're going to assume this is the value. + if (! is_numeric($key)) { + return [ + $this->valueField => $key, + $this->labelField => $value, + ]; + } + + // If the value is a simple value, we need to convert it to an array. + if (! is_iterable($value) && ! $value instanceof Model) { + return [ + $this->valueField => $value, + $this->labelField => $value, + ]; + } + + return $value; + }); + } } diff --git a/tests/Components/Inputs/SelectTest.php b/tests/Components/Inputs/SelectTest.php index b9c8e4d..e7fa377 100644 --- a/tests/Components/Inputs/SelectTest.php +++ b/tests/Components/Inputs/SelectTest.php @@ -307,3 +307,34 @@ }) ->assertSeeInOrder(['Germany', 'Canada', 'United States', 'France']); }); + +test('simple array options are supported', function () { + $options = [ + 'option_1', + 'option_2', + ]; + + $template = <<<'HTML' +
+ + + HTML; + + Route::get('/test', fn () => Blade::render($template, ['options' => $options])); + + get('/test') + ->assertFormExists('form', function (AssertForm $form) { + $form->findSelect('select', function (AssertSelect $select) { + $select->containsOptions( + [ + 'value' => 'option_1', + 'text' => 'option_1', + ], + [ + 'value' => 'option_2', + 'text' => 'option_2', + ], + ); + }); + }); +});