Skip to content
This repository was archived by the owner on Jan 2, 2024. It is now read-only.

Commit 23688ca

Browse files
committed
Add support for Enum as selected item in FormSelect
Lint Correct enum support Add tests
1 parent d4bf426 commit 23688ca

File tree

4 files changed

+59
-0
lines changed

4 files changed

+59
-0
lines changed

src/Components/FormSelect.php

+8
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,14 @@ public function __construct(
5454
if ($this->selectedKey instanceof Arrayable) {
5555
$this->selectedKey = $this->selectedKey->toArray();
5656
}
57+
58+
if ($this->selectedKey instanceof \BackedEnum) {
59+
$this->selectedKey = $this->selectedKey->value;
60+
}
61+
62+
if ($this->selectedKey instanceof \UnitEnum) {
63+
$this->selectedKey = $this->selectedKey->name;
64+
}
5765
}
5866

5967
$this->multiple = $multiple;

tests/Feature/SelectTest.php

+41
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,24 @@
44

55
use ProtoneMedia\LaravelFormComponents\Tests\TestCase;
66

7+
enum TestEnum: int
8+
{
9+
case a = 1;
10+
case b = 2;
11+
case c = 3;
12+
13+
public static function toOptions(): array
14+
{
15+
$formattedCases = [];
16+
17+
foreach (self::cases() as $option) {
18+
$formattedCases[$option->value] = $option->name;
19+
}
20+
21+
return $formattedCases;
22+
}
23+
}
24+
725
class SelectTest extends TestCase
826
{
927
/** @test */
@@ -27,4 +45,27 @@ public function it_can_render_a_placeholder()
2745
->seeElement('option[value="a"]')
2846
->seeElement('option[value="b"]');
2947
}
48+
49+
/** @test */
50+
public function it_can_render_a_selected_option()
51+
{
52+
$this->registerTestRoute('select-selected');
53+
$this->session(['_old_input' => ['select' => 'a']]);
54+
55+
$this->visit('/select-selected')
56+
->seeElement('option[value="a"][selected="selected"]')
57+
->seeElement('option[value="b"]');
58+
}
59+
60+
/** @test */
61+
public function it_can_render_a_selected_enum_option()
62+
{
63+
$this->registerTestRoute('select-selected-enum');
64+
$this->session(['_old_input' => ['select' => TestEnum::a]]);
65+
66+
$this->visit('/select-selected-enum')
67+
->seeElement('option[value="1"][selected="selected"]')
68+
->seeElement('option[value="2"]')
69+
->seeElement('option[value="3"]');
70+
}
3071
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<x-form>
2+
<x-form-select name="select" :options="\ProtoneMedia\LaravelFormComponents\Tests\Feature\TestEnum::toOptions()"></x-form-select>
3+
4+
<x-form-submit />
5+
</x-form>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<x-form>
2+
<x-form-select name="select" :options="['a' => 'a', 'b' => 'b']"></x-form-select>
3+
4+
<x-form-submit />
5+
</x-form>

0 commit comments

Comments
 (0)