Browse Source

Merge pull request #15706 from cakephp/fix-15700-backport

3.x - Fix radio inputs trimming leading - off causing duplicate ids
othercorey 4 years ago
parent
commit
c105bd5527

+ 1 - 1
src/View/Widget/RadioWidget.php

@@ -165,7 +165,7 @@ class RadioWidget implements WidgetInterface
 
         if (empty($radio['id'])) {
             if (isset($data['id'])) {
-                $radio['id'] = $data['id'] . '-' . trim(
+                $radio['id'] = $data['id'] . '-' . rtrim(
                     $this->_idSuffix($radio['value']),
                     '-'
                 );

+ 33 - 0
tests/TestCase/View/Helper/FormHelperTest.php

@@ -4902,6 +4902,39 @@ class FormHelperTest extends TestCase
             '/div',
         ];
         $this->assertHtml($expected, $result);
+
+        $result = $this->Form->control('accept', [
+            'type' => 'radio',
+            'options' => [
+                1 => 'positive',
+                -1 => 'negative',
+            ],
+            'label' => false,
+        ]);
+        $expected = [
+            ['div' => ['class' => 'input radio']],
+                ['input' => ['type' => 'hidden', 'name' => 'accept', 'value' => '']],
+                ['label' => ['for' => 'accept-1']],
+                ['input' => [
+                    'type' => 'radio',
+                    'name' => 'accept',
+                    'value' => '1',
+                    'id' => 'accept-1',
+                ]],
+                'positive',
+                '/label',
+                ['label' => ['for' => 'accept--1']],
+                ['input' => [
+                    'type' => 'radio',
+                    'name' => 'accept',
+                    'value' => '-1',
+                    'id' => 'accept--1',
+                ]],
+                'negative',
+                '/label',
+            '/div',
+        ];
+        $this->assertHtml($expected, $result);
     }
 
     /**

+ 7 - 1
tests/TestCase/View/Widget/RadioWidgetTest.php

@@ -835,7 +835,7 @@ class RadioWidgetTest extends TestCase
         $input = new RadioWidget($this->templates, $label);
         $data = [
             'name' => 'field',
-            'options' => ['value1', 'value2'],
+            'options' => ['value1', 'value2', -1 => 'negative'],
             'id' => 'alternative-id',
             'idPrefix' => 'willBeIgnored',
         ];
@@ -853,6 +853,12 @@ class RadioWidgetTest extends TestCase
             ],
             'value2',
             '/label',
+            [
+                'label' => ['for' => 'alternative-id--1'],
+                'input' => ['type' => 'radio', 'name' => 'field', 'value' => '-1', 'id' => 'alternative-id--1'],
+            ],
+            'negative',
+            '/label',
         ];
         $this->assertHtml($expected, $result);