Browse Source

Add support for recognizing errors on belongsToMany selects

While it is possible to validate fields for belongsToMany selects,
this must be done using the plain association property, and so the
form helper will not able to pick up possible errors, as it will
check for the fieldname with `._ids` appended.
ndm2 11 years ago
parent
commit
2da0157219
2 changed files with 48 additions and 0 deletions
  1. 3 0
      src/View/Helper/FormHelper.php
  2. 45 0
      tests/TestCase/View/Helper/FormHelperTest.php

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

@@ -674,6 +674,9 @@ class FormHelper extends Helper
      */
     public function error($field, $text = null, array $options = [])
     {
+        if (substr($field, -5) === '._ids') {
+            $field = substr($field, 0, -5);
+        }
         $options += ['escape' => true];
 
         $context = $this->_getContext();

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

@@ -4157,6 +4157,51 @@ class FormHelperTest extends TestCase
     }
 
     /**
+     * Tests that errors for belongsToMany select fields are being
+     * picked up properly.
+     *
+     * @return void
+     */
+    public function testErrorsForBelongsToManySelect()
+    {
+        $tags = [
+            1 => 'blue',
+            50 => 'green'
+        ];
+        $this->View->viewVars['tags'] = $tags;
+
+        $article = new Article();
+        $article->errors('tags', ['Invalid']);
+
+        $this->Form->create($article);
+        $result = $this->Form->input('tags._ids');
+
+        $expected = [
+            ['div' => ['class' => 'input select error']],
+            'label' => ['for' => 'tags-ids'],
+            'Tags',
+            '/label',
+            'input' => ['type' => 'hidden', 'name' => 'tags[_ids]', 'value' => ''],
+            'select' => [
+                'name' => 'tags[_ids][]', 'id' => 'tags-ids',
+                'multiple' => 'multiple'
+            ],
+            ['option' => ['value' => '1']],
+            'blue',
+            '/option',
+            ['option' => ['value' => '50']],
+            'green',
+            '/option',
+            '/select',
+            ['div' => ['class' => 'error-message']],
+            'Invalid',
+            '/div',
+            '/div'
+        ];
+        $this->assertHtml($expected, $result);
+    }
+
+    /**
      * test generation of multi select elements in checkbox format
      *
      * @return void