Browse Source

Add magic options support for belongsToMany selects

This already works for belongsTo associations, making it work for
belongsToMany might come in handy too.

Using `substr()` as in other places, it's way faster than a regex,
and there is no complexity involved that would make a regex
necessary.
ndm2 11 years ago
parent
commit
8cf081f304
2 changed files with 35 additions and 1 deletions
  1. 7 1
      src/View/Helper/FormHelper.php
  2. 28 0
      tests/TestCase/View/Helper/FormHelperTest.php

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

@@ -1167,9 +1167,15 @@ class FormHelper extends Helper
             return $options;
         }
 
+        if (substr($fieldName, -5) === '._ids') {
+            $fieldName = substr($fieldName, 0, -5);
+        }
+        if (substr($fieldName, -3) === '_id') {
+            $fieldName = substr($fieldName, 0, -3);
+        }
         $fieldName = array_slice(explode('.', $fieldName), -1)[0];
         $varName = Inflector::variable(
-            Inflector::pluralize(preg_replace('/_id$/', '', $fieldName))
+            Inflector::pluralize($fieldName)
         );
         $varOptions = $this->_View->get($varName);
         if (!is_array($varOptions) && !($varOptions instanceof Traversable)) {

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

@@ -4126,6 +4126,34 @@ class FormHelperTest extends TestCase
             '/div'
         ];
         $this->assertHtml($expected, $result);
+
+        $tags = [
+            1 => 'blue',
+            50 => 'green'
+        ];
+        $this->View->viewVars['tags'] = $tags;
+        $this->Form->create();
+        $result = $this->Form->input('tags._ids');
+        $expected = [
+            'div' => ['class' => 'input select'],
+            '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'
+        ];
+        $this->assertHtml($expected, $result);
     }
 
     /**