Skip to content

Commit 470b122

Browse files
Support Opt-Groups (#97)
1 parent 170df7d commit 470b122

File tree

2 files changed

+42
-3
lines changed

2 files changed

+42
-3
lines changed

tests/Unit/SelectTest.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,29 @@ public function test_an_empty_option_can_be_prepended_to_a_non_associative_array
8585
$this->assertSelectorTextEquals($html, 'option[value="2"]', 'Ann Patchett');
8686
}
8787

88+
public function test_opt_groups_render_properly_along_side_regular_select_options() : void
89+
{
90+
$options = [
91+
'Language' => [
92+
'php' => 'PHP',
93+
'js' => 'JavaScript',
94+
],
95+
1 => 'Philip Roth',
96+
];
97+
98+
$html = $this->aire()->select($options)->render();
99+
100+
$this->assertSelectorAttribute($html, 'select > optgroup', 'label', 'Language');
101+
102+
$this->assertSelectorTextEquals($html, 'select > optgroup > option:nth-of-type(1)', 'PHP');
103+
$this->assertSelectorAttribute($html, 'select > optgroup > option:nth-of-type(1)', 'value', 'php');
104+
105+
$this->assertSelectorTextEquals($html, 'select > optgroup > option:nth-of-type(2)', 'JavaScript');
106+
$this->assertSelectorAttribute($html, 'select > optgroup > option:nth-of-type(2)', 'value', 'js');
107+
108+
$this->assertSelectorTextEquals($html, 'select > option[value="1"]', 'Philip Roth');
109+
}
110+
88111
public function test_an_enum_class_name_will_be_converted_to_a_selectable_array() : void
89112
{
90113
if (!class_exists('BenSampo\Enum\Enum')) {

views/select.blade.php

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,25 @@
1111

1212
@foreach($options->getOptions() as $value => $label)
1313

14-
<option value="{{ $value }}" {{ $attributes->isValue($value) ? 'selected' : '' }}>
15-
{{ $label }}
16-
</option>
14+
@if(is_array($label))
15+
16+
<optgroup label="{{ $value }}">
17+
18+
@foreach($label as $value => $nestedLabel)
19+
<option value="{{ $value }}" {{ $attributes->isValue($value) ? 'selected' : '' }}>
20+
{{ $nestedLabel }}
21+
</option>
22+
@endforeach
23+
24+
</optgroup>
25+
26+
@else
27+
28+
<option value="{{ $value }}" {{ $attributes->isValue($value) ? 'selected' : '' }}>
29+
{{ $label }}
30+
</option>
31+
32+
@endif
1733

1834
@endforeach
1935

0 commit comments

Comments
 (0)