From 5642564ac5a6629f1d8e073eabf84f4934b21311 Mon Sep 17 00:00:00 2001 From: Brian Porter Date: Sun, 6 Dec 2015 05:53:35 -0600 Subject: [PATCH] Update FormContext::errors() to handle nested errors. Adjust error collection to properly handle nested validators. Partially addresses #7532. --- src/View/Form/FormContext.php | 7 ++----- tests/TestCase/View/Form/FormContextTest.php | 15 +++++++++++++-- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/src/View/Form/FormContext.php b/src/View/Form/FormContext.php index c4d38932339..e29ef892630 100644 --- a/src/View/Form/FormContext.php +++ b/src/View/Form/FormContext.php @@ -15,6 +15,7 @@ namespace Cake\View\Form; use Cake\Network\Request; +use Cake\Utility\Hash; /** * Provides a context provider for Cake\Form\Form instances. @@ -134,10 +135,6 @@ public function hasError($field) */ public function error($field) { - $errors = $this->_form->errors(); - if (isset($errors[$field])) { - return array_values($errors[$field]); - } - return []; + return array_values(Hash::get($this->_form->errors(), $field, [])); } } diff --git a/tests/TestCase/View/Form/FormContextTest.php b/tests/TestCase/View/Form/FormContextTest.php index 624515a9152..0e45c492a91 100644 --- a/tests/TestCase/View/Form/FormContextTest.php +++ b/tests/TestCase/View/Form/FormContextTest.php @@ -17,6 +17,7 @@ use Cake\Form\Form; use Cake\Network\Request; use Cake\TestSuite\TestCase; +use Cake\Validation\Validator; use Cake\View\Form\FormContext; /** @@ -172,19 +173,29 @@ public function testAttributes() */ public function testError() { + $nestedValidator = new Validator(); + $nestedValidator + ->add('password', 'length', ['rule' => ['minLength', 8]]) + ->add('confirm', 'length', ['rule' => ['minLength', 8]]); $form = new Form(); $form->validator() ->add('email', 'format', ['rule' => 'email']) - ->add('name', 'length', ['rule' => ['minLength', 10]]); + ->add('name', 'length', ['rule' => ['minLength', 10]]) + ->addNested('pass', $nestedValidator); $form->validate([ 'email' => 'derp', - 'name' => 'derp' + 'name' => 'derp', + 'pass' => [ + 'password' => 'short', + 'confirm' => 'long enough', + ], ]); $context = new FormContext($this->request, ['entity' => $form]); $this->assertEquals([], $context->error('empty')); $this->assertEquals(['The provided value is invalid'], $context->error('email')); $this->assertEquals(['The provided value is invalid'], $context->error('name')); + $this->assertEquals(['The provided value is invalid'], $context->error('pass.password')); $this->assertEquals([], $context->error('Alias.name')); $this->assertEquals([], $context->error('nope.nope'));