Browse Source

Implemented a change in Entity::errors() so that nested errors are returned

This is a common request and something that had to be hacked in DebugKit.
With the changes done in validation, this is a required change as there would
be no other way of telling wheter a validation routine set any errors in nested
entities.
Jose Lorenzo Rodriguez 11 years ago
parent
commit
a24e1e4efc
2 changed files with 21 additions and 2 deletions
  1. 13 2
      src/Datasource/EntityTrait.php
  2. 8 0
      tests/TestCase/ORM/EntityTest.php

+ 13 - 2
src/Datasource/EntityTrait.php

@@ -16,6 +16,7 @@ namespace Cake\Datasource;
 
 use Cake\Utility\Inflector;
 use Cake\Validation\Validator;
+use Cake\Collection\Collection;
 use Traversable;
 
 /**
@@ -607,7 +608,8 @@ trait EntityTrait {
  * Sets the error messages for a field or a list of fields. When called
  * without the second argument it returns the validation
  * errors for the specified fields. If called with no arguments it returns
- * all the validation error messages stored in this entity.
+ * all the validation error messages stored in this entity and any other nested
+ * entity.
  *
  * ### Example
  *
@@ -635,7 +637,16 @@ trait EntityTrait {
  */
 	public function errors($field = null, $errors = null, $overwrite = false) {
 		if ($field === null) {
-			return $this->_errors;
+			$diff = array_diff_key($this->_properties, $this->_errors);
+			return $this->_errors + (new Collection($diff))
+				->filter(function ($value) {
+					return is_array($value) || $value instanceof EntityInterface;
+				})
+				->map(function ($value) {
+					return $this->_readError($value);
+				})
+				->filter()
+				->toArray();
 		}
 
 		if (is_string($field) && $errors === null) {

+ 8 - 0
tests/TestCase/ORM/EntityTest.php

@@ -848,6 +848,14 @@ class EntityTest extends TestCase {
 			['c' => ['error3'], 'd' => ['error4']]
 		];
 		$this->assertEquals($expected, $author->errors('multiple'));
+
+		$expected = [
+			'thing' => $author->errors('thing'),
+			'user' => $author->errors('user'),
+			'owner' => $author->errors('owner'),
+			'multiple' => $author->errors('multiple')
+		];
+		$this->assertEquals($expected, $author->errors());
 	}
 
 /**