Skip to content

Commit

Permalink
Update FormContext::errors() to handle nested errors.
Browse files Browse the repository at this point in the history
Adjust error collection to properly handle nested validators. Partially addresses #7532.
  • Loading branch information
beporter committed Dec 6, 2015
1 parent dafe49e commit 5642564
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
7 changes: 2 additions & 5 deletions src/View/Form/FormContext.php
Expand Up @@ -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.
Expand Down Expand Up @@ -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, []));
}
}
15 changes: 13 additions & 2 deletions tests/TestCase/View/Form/FormContextTest.php
Expand Up @@ -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;

/**
Expand Down Expand Up @@ -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'));
Expand Down

0 comments on commit 5642564

Please sign in to comment.