Skip to content

Commit

Permalink
Add magic options support for belongsToMany selects
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
ndm2 committed Feb 23, 2015
1 parent 4739d83 commit 8cf081f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/View/Helper/FormHelper.php
Expand Up @@ -1167,9 +1167,15 @@ protected function _optionsOptions($fieldName, $options)
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)) {
Expand Down
28 changes: 28 additions & 0 deletions tests/TestCase/View/Helper/FormHelperTest.php
Expand Up @@ -4126,6 +4126,34 @@ public function testHabtmSelectBox()
'/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);
}

/**
Expand Down

0 comments on commit 8cf081f

Please sign in to comment.