From 2da01572193c05e4fe4ca0315d665b35353fbb75 Mon Sep 17 00:00:00 2001 From: ndm2 Date: Mon, 23 Feb 2015 09:53:49 +0100 Subject: [PATCH] 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. --- src/View/Helper/FormHelper.php | 3 ++ tests/TestCase/View/Helper/FormHelperTest.php | 45 +++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/src/View/Helper/FormHelper.php b/src/View/Helper/FormHelper.php index 2f10f85742c..f436fed8998 100644 --- a/src/View/Helper/FormHelper.php +++ b/src/View/Helper/FormHelper.php @@ -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(); diff --git a/tests/TestCase/View/Helper/FormHelperTest.php b/tests/TestCase/View/Helper/FormHelperTest.php index 355116ba5ec..10c9fa15171 100644 --- a/tests/TestCase/View/Helper/FormHelperTest.php +++ b/tests/TestCase/View/Helper/FormHelperTest.php @@ -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 *