Browse Source

Automatically setting the entity provider inside EntityContext

This was required as now the outcome of isEmptyAllowed could change based on
what is contained inside the entity object
Jose Lorenzo Rodriguez 11 years ago
parent
commit
f79729b4de
2 changed files with 35 additions and 1 deletions
  1. 16 1
      src/View/Form/EntityContext.php
  2. 19 0
      tests/TestCase/View/Form/EntityContextTest.php

+ 16 - 1
src/View/Form/EntityContext.php

@@ -81,6 +81,13 @@ class EntityContext implements ContextInterface {
 	protected $_tables = [];
 
 /**
+ * A Hash of validators indexed by the entity key
+ *
+ * @var array
+ */
+	protected $_validator = [];
+
+/**
  * Constructor.
  *
  * @param \Cake\Network\Request $request The request object.
@@ -345,6 +352,11 @@ class EntityContext implements ContextInterface {
  * @return \Cake\Validation\Validator
  */
 	protected function _getValidator($parts) {
+		$key = implode('.', $parts);
+		if (isset($this->_validator[$key])) {
+			return $this->_validator[$key];
+		}
+
 		$table = $this->_getTable($parts);
 		$alias = $table->alias();
 
@@ -354,7 +366,10 @@ class EntityContext implements ContextInterface {
 		} elseif (isset($this->_context['validator'][$alias])) {
 			$method = $this->_context['validator'][$alias];
 		}
-		return $table->validator($method);
+
+		$validator = $table->validator($method);
+		$validator->provider('entity', $this->_context['entity']);
+		return $this->_validator[$key] = $validator;
 	}
 
 /**

+ 19 - 0
tests/TestCase/View/Form/EntityContextTest.php

@@ -883,4 +883,23 @@ class EntityContextTest extends TestCase {
 		$this->assertEquals($articles->schema()->columns(), $context->fieldNames());
 	}
 
+/**
+ * Test automatic entity provider setting
+ *
+ * @return void
+ */
+	public function testValidatorEntityProvider() {
+		$row = new Article([
+			'title' => 'Test entity',
+			'body' => 'Something new'
+		]);
+		$context = new EntityContext($this->request, [
+			'entity' => $row,
+			'table' => 'Articles',
+		]);
+		$context->isRequired('title');
+		$articles = TableRegistry::get('Articles');
+		$this->assertSame($row,  $articles->validator()->provider('entity'));
+	}
+
 }