Browse Source

Add classname reflection to get table names when argument is omitted.

mark_story 12 years ago
parent
commit
2a87be0cd5
2 changed files with 42 additions and 0 deletions
  1. 13 0
      src/View/Form/EntityContext.php
  2. 29 0
      tests/TestCase/View/Form/EntityContextTest.php

+ 13 - 0
src/View/Form/EntityContext.php

@@ -17,6 +17,7 @@ namespace Cake\View\Form;
 use Cake\Network\Request;
 use Cake\ORM\Entity;
 use Cake\ORM\TableRegistry;
+use Cake\Utility\Inflector;
 use Cake\Validation\Validator;
 use Traversable;
 
@@ -92,9 +93,21 @@ class EntityContext {
  */
 	protected function _prepare() {
 		$table = $this->_context['table'];
+		if (empty($table)) {
+			$entity = $this->_context['entity'];
+			if ($entity instanceof Entity) {
+				list($ns, $entityClass) = namespaceSplit(get_class($entity));
+				$table = Inflector::pluralize($entityClass);
+			}
+		}
 		if (is_string($table)) {
 			$table = TableRegistry::get($table);
 		}
+		if (!is_object($table)) {
+			throw new \RuntimeException(
+				'Unable to find table class for current entity'
+			);
+		}
 		$alias = $this->_rootName = $table->alias();
 		$this->_tables[$alias] = $table;
 	}

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

@@ -23,6 +23,12 @@ use Cake\Validation\Validator;
 use Cake\View\Form\EntityContext;
 
 /**
+ * Test stub.
+ */
+class Article extends Entity {
+}
+
+/**
  * Entity context test case.
  */
 class EntityContextTest extends TestCase {
@@ -45,6 +51,29 @@ class EntityContextTest extends TestCase {
 	}
 
 /**
+ * Test operations that lack a table argument.
+ *
+ * @return void
+ */
+	public function testOperationsNoTableArg() {
+		$row = new Article([
+			'title' => 'Test entity',
+			'body' => 'Something new'
+		]);
+		$row->errors('title', ['Title is required.']);
+
+		$context = new EntityContext($this->request, [
+			'entity' => $row,
+		]);
+
+		$result = $context->val('title');
+		$this->assertEquals($row->title, $result);
+
+		$result = $context->error('title');
+		$this->assertEquals($row->errors('title'), $result);
+	}
+
+/**
  * Test reading data.
  *
  * @return void