diff --git a/src/Components/FormSelect.php b/src/Components/FormSelect.php index 12b0600..059c360 100644 --- a/src/Components/FormSelect.php +++ b/src/Components/FormSelect.php @@ -54,6 +54,14 @@ public function __construct( if ($this->selectedKey instanceof Arrayable) { $this->selectedKey = $this->selectedKey->toArray(); } + + if ($this->selectedKey instanceof \BackedEnum) { + $this->selectedKey = $this->selectedKey->value; + } + + if ($this->selectedKey instanceof \UnitEnum) { + $this->selectedKey = $this->selectedKey->name; + } } $this->multiple = $multiple; diff --git a/tests/Feature/SelectTest.php b/tests/Feature/SelectTest.php index 3f3f96b..f56772c 100644 --- a/tests/Feature/SelectTest.php +++ b/tests/Feature/SelectTest.php @@ -4,6 +4,24 @@ use ProtoneMedia\LaravelFormComponents\Tests\TestCase; +enum TestEnum: int +{ + case a = 1; + case b = 2; + case c = 3; + + public static function toOptions(): array + { + $formattedCases = []; + + foreach (self::cases() as $option) { + $formattedCases[$option->value] = $option->name; + } + + return $formattedCases; + } +} + class SelectTest extends TestCase { /** @test */ @@ -27,4 +45,27 @@ public function it_can_render_a_placeholder() ->seeElement('option[value="a"]') ->seeElement('option[value="b"]'); } + + /** @test */ + public function it_can_render_a_selected_option() + { + $this->registerTestRoute('select-selected'); + $this->session(['_old_input' => ['select' => 'a']]); + + $this->visit('/select-selected') + ->seeElement('option[value="a"][selected="selected"]') + ->seeElement('option[value="b"]'); + } + + /** @test */ + public function it_can_render_a_selected_enum_option() + { + $this->registerTestRoute('select-selected-enum'); + $this->session(['_old_input' => ['select' => TestEnum::a]]); + + $this->visit('/select-selected-enum') + ->seeElement('option[value="1"][selected="selected"]') + ->seeElement('option[value="2"]') + ->seeElement('option[value="3"]'); + } } diff --git a/tests/Feature/views/select-selected-enum.blade.php b/tests/Feature/views/select-selected-enum.blade.php new file mode 100644 index 0000000..8b69ca6 --- /dev/null +++ b/tests/Feature/views/select-selected-enum.blade.php @@ -0,0 +1,5 @@ +<x-form> + <x-form-select name="select" :options="\ProtoneMedia\LaravelFormComponents\Tests\Feature\TestEnum::toOptions()"></x-form-select> + + <x-form-submit /> +</x-form> diff --git a/tests/Feature/views/select-selected.blade.php b/tests/Feature/views/select-selected.blade.php new file mode 100644 index 0000000..8616e55 --- /dev/null +++ b/tests/Feature/views/select-selected.blade.php @@ -0,0 +1,5 @@ +<x-form> + <x-form-select name="select" :options="['a' => 'a', 'b' => 'b']"></x-form-select> + + <x-form-submit /> +</x-form>