diff --git a/Cake/View/Input/SelectBox.php b/Cake/View/Input/SelectBox.php index 15dd928ab94..5f65d5fa181 100644 --- a/Cake/View/Input/SelectBox.php +++ b/Cake/View/Input/SelectBox.php @@ -130,14 +130,20 @@ protected function _renderContent($data) { protected function _renderOptions($options, $disabled, $selected, $escape) { $out = []; foreach ($options as $key => $val) { - if (is_array($val) || $val instanceof Traversable) { + if (!is_int($key) && is_array($val) || $val instanceof Traversable) { $groupOptions = $this->_renderOptions($val, $disabled, $selected, $escape); $out[] = $this->_templates->format('optgroup', [ 'label' => $escape ? h($key) : $key, 'content' => implode('', $groupOptions) ]); } else { - $optAttrs = []; + $optAttrs = [ + 'name' => $key, + 'value' => $val, + ]; + if (is_array($val) && isset($optAttrs['name'], $optAttrs['value'])) { + $optAttrs = $val; + } if ($this->_isSelected($key, $selected)) { $optAttrs['selected'] = true; } @@ -147,9 +153,9 @@ protected function _renderOptions($options, $disabled, $selected, $escape) { $optAttrs['escape'] = $escape; $out[] = $this->_templates->format('option', [ - 'name' => $escape ? h($key) : $key, - 'value' => $escape ? h($val) : $val, - 'attrs' => $this->_templates->formatAttributes($optAttrs), + 'name' => $escape ? h($optAttrs['name']) : $optAttrs['name'], + 'value' => $escape ? h($optAttrs['value']) : $optAttrs['value'], + 'attrs' => $this->_templates->formatAttributes($optAttrs, ['name', 'value']), ]); } } diff --git a/Test/TestCase/View/Input/SelectBoxTest.php b/Test/TestCase/View/Input/SelectBoxTest.php index ab55555dfba..af5d0c84574 100644 --- a/Test/TestCase/View/Input/SelectBoxTest.php +++ b/Test/TestCase/View/Input/SelectBoxTest.php @@ -76,6 +76,36 @@ public function testRenderSimple() { $this->assertTags($result, $expected); } +/** + * test complex option rendering + * + * @return void + */ + public function testRenderComplex() { + $select = new SelectBox($this->templates); + $data = [ + 'id' => 'BirdName', + 'name' => 'Birds[name]', + 'options' => [ + ['name' => 'a', 'value' => 'Albatross'], + ['name' => 'b', 'value' => 'Budgie', 'data-foo' => 'bar'], + ] + ]; + $result = $select->render($data); + $expected = [ + 'select' => ['name' => 'Birds[name]', 'id' => 'BirdName'], + ['option' => ['value' => 'a']], + 'Albatross', + '/option', + ['option' => ['value' => 'b', 'data-foo' => 'bar']], + 'Budgie', + '/option', + '/select' + ]; + $this->assertTags($result, $expected); + } + + /** * test rendering with a selected value *