Skip to content

Commit

Permalink
Add support for recognizing errors on belongsToMany selects
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
ndm2 committed Feb 23, 2015
1 parent 8cf081f commit 2da0157
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/View/Helper/FormHelper.php
Expand Up @@ -674,6 +674,9 @@ public function isFieldError($field)
*/
public function error($field, $text = null, array $options = [])
{
if (substr($field, -5) === '._ids') {
$field = substr($field, 0, -5);
}
$options += ['escape' => true];

$context = $this->_getContext();
Expand Down
45 changes: 45 additions & 0 deletions tests/TestCase/View/Helper/FormHelperTest.php
Expand Up @@ -4156,6 +4156,51 @@ public function testHabtmSelectBox()
$this->assertHtml($expected, $result);
}

/**
* 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
*
Expand Down

0 comments on commit 2da0157

Please sign in to comment.