Browse Source

Handle optgroups with integer values better.

Instead of failing on these keys because they are integers, also check
for the 'value' key being missing. This key missing is a pretty clear
indication that the option is not a complex option definition, and
likely an optgroup.

Refs #7361
Mark Story 10 years ago
parent
commit
3d6eb08e0c

+ 2 - 2
src/View/Widget/SelectBoxWidget.php

@@ -228,7 +228,7 @@ class SelectBoxWidget extends BasicWidget
             // Option groups
             $arrayVal = (is_array($val) || $val instanceof Traversable);
             if ((!is_int($key) && $arrayVal) ||
-                (is_int($key) && $arrayVal && isset($val['options']))
+                (is_int($key) && $arrayVal && (isset($val['options']) || !isset($val['value'])))
             ) {
                 $out[] = $this->_renderOptgroup($key, $val, $disabled, $selected, $escape);
                 continue;
@@ -239,7 +239,7 @@ class SelectBoxWidget extends BasicWidget
                 'value' => $key,
                 'text' => $val,
             ];
-            if (is_array($val) && isset($optAttrs['text'], $optAttrs['value'])) {
+            if (is_array($val) && isset($val['text'], $val['value'])) {
                 $optAttrs = $val;
                 $key = $optAttrs['value'];
             }

+ 42 - 0
tests/TestCase/View/Widget/SelectBoxWidgetTest.php

@@ -353,6 +353,48 @@ class SelectBoxWidgetTest extends TestCase
     }
 
     /**
+     * test rendering with numeric option group keys
+     *
+     * @return void
+     */
+    public function testRenderOptionGroupsIntegerKeys()
+    {
+        $select = new SelectBoxWidget($this->templates);
+        $data = [
+            'name' => 'Year[key]',
+            'options' => [
+                2014 => [
+                    'key' => 'value'
+                ],
+                2013 => [
+                    'text' => '2013-text',
+                    'options' => [
+                        'key2' => 'value2'
+                    ]
+                ]
+            ]
+        ];
+        $result = $select->render($data, $this->context);
+        $expected = [
+            'select' => [
+                'name' => 'Year[key]',
+            ],
+            ['optgroup' => ['label' => '2014']],
+            ['option' => ['value' => 'key']],
+            'value',
+            '/option',
+            '/optgroup',
+            ['optgroup' => ['label' => '2013-text']],
+            ['option' => ['value' => 'key2']],
+            'value2',
+            '/option',
+            '/optgroup',
+            '/select'
+        ];
+        $this->assertHtml($expected, $result);
+    }
+
+    /**
      * test rendering with option groups and escaping
      *
      * @return void