Browse Source

Making EntityContext more intelligent by reading the entity source

Jose Lorenzo Rodriguez 12 years ago
parent
commit
57d283842a
2 changed files with 22 additions and 1 deletions
  1. 7 1
      src/View/Form/EntityContext.php
  2. 15 0
      tests/TestCase/View/Form/EntityContextTest.php

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

@@ -120,7 +120,13 @@ class EntityContext implements ContextInterface {
 			if (is_array($entity) || $entity instanceof Traversable) {
 				$entity = (new Collection($entity))->first();
 			}
-			if ($entity instanceof Entity && get_class($entity) !== 'Cake\ORM\Entity') {
+			$isEntity = $entity instanceof Entity;
+
+			if ($isEntity) {
+				$source = $entity->source();
+				$table = isset($source['alias']) ? $source['alias'] : null;
+			}
+			if (!$table && $isEntity && get_class($entity) !== 'Cake\ORM\Entity') {
 				list($ns, $entityClass) = namespaceSplit(get_class($entity));
 				$table = Inflector::pluralize($entityClass);
 			}

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

@@ -144,6 +144,21 @@ class EntityContextTest extends TestCase {
 	}
 
 /**
+ * Tests that the table can be derived from the entity source if it is present
+ *
+ * @return void
+ */
+	public function testTableFromEntitySource() {
+		$entity = new Entity;
+		$entity->source(['alias' => 'Articles']);
+		$context = new EntityContext($this->request, [
+			'entity' => $entity,
+		]);
+		$expected = ['id', 'author_id', 'title', 'body', 'published'];
+		$this->assertEquals($expected, $context->fieldNames());
+	}
+
+/**
  * Test operations with no entity.
  *
  * @return void