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

Add support for Enum as selected item in FormSelect #110

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/Components/FormSelect.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
41 changes: 41 additions & 0 deletions tests/Feature/SelectTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
Expand All @@ -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"]');
}
}
5 changes: 5 additions & 0 deletions tests/Feature/views/select-selected-enum.blade.php
Original file line number Diff line number Diff line change
@@ -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>
5 changes: 5 additions & 0 deletions tests/Feature/views/select-selected.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<x-form>
<x-form-select name="select" :options="['a' => 'a', 'b' => 'b']"></x-form-select>

<x-form-submit />
</x-form>