Browse Source

Fix custom id problem in multiCheckbox()

Much like the problem in radio() this method is also impacted. Shout out
to @ndm2 who identified this issue during review.
Mark Story 3 years ago
parent
commit
56033f0ff3
2 changed files with 39 additions and 1 deletions
  1. 3 1
      src/View/Helper/FormHelper.php
  2. 36 0
      tests/TestCase/View/Helper/FormHelperTest.php

+ 3 - 1
src/View/Helper/FormHelper.php

@@ -2118,8 +2118,10 @@ class FormHelper extends Helper
             'secure' => true,
         ];
 
+        $generatedHiddenId = false;
         if (!isset($attributes['id'])) {
             $attributes['id'] = true;
+            $generatedHiddenId = true;
         }
 
         $attributes = $this->_initInputField($fieldName, $attributes);
@@ -2139,7 +2141,7 @@ class FormHelper extends Helper
         }
         unset($attributes['hiddenField']);
 
-        if (!isset($attributes['type']) && isset($attributes['name'])) {
+        if ($generatedHiddenId) {
             unset($attributes['id']);
         }
 

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

@@ -5657,6 +5657,42 @@ class FormHelperTest extends TestCase
     }
 
     /**
+     * testSelectCheckboxMultipleOverrideName method
+     *
+     * Test that select() with multiple = checkbox works with overriding name attribute.
+     */
+    public function testSelectCheckboxMultipleCustomId(): void
+    {
+        $result = $this->Form->select('category', ['1', '2'], [
+            'multiple' => 'checkbox',
+            'id' => 'cat',
+        ]);
+        $expected = [
+            'input' => ['type' => 'hidden', 'name' => 'category', 'value' => '', 'id' => 'cat'],
+            ['div' => ['class' => 'checkbox']],
+                ['label' => ['for' => 'cat-0']],
+                    ['input' => ['type' => 'checkbox', 'name' => 'category[]', 'value' => '0', 'id' => 'cat-0']],
+                    '1',
+                '/label',
+            '/div',
+            ['div' => ['class' => 'checkbox']],
+                ['label' => ['for' => 'cat-1']],
+                    ['input' => ['type' => 'checkbox', 'name' => 'category[]', 'value' => '1', 'id' => 'cat-1']],
+                    '2',
+                '/label',
+            '/div',
+        ];
+        $this->assertHtml($expected, $result);
+
+        $result = $this->Form->multiCheckbox(
+            'category',
+            ['1', '2'],
+            ['id' => 'cat']
+        );
+        $this->assertHtml($expected, $result);
+    }
+
+    /**
      * testControlMultiCheckbox method
      *
      * Test that control() works with multicheckbox.