From 2a87be0cd5a10ed437b1e199d214802e84442e4b Mon Sep 17 00:00:00 2001 From: mark_story Date: Tue, 4 Feb 2014 21:51:53 -0500 Subject: [PATCH] Add classname reflection to get table names when argument is omitted. --- src/View/Form/EntityContext.php | 13 +++++++++ .../TestCase/View/Form/EntityContextTest.php | 29 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/src/View/Form/EntityContext.php b/src/View/Form/EntityContext.php index 9180531f72d..d818cb98160 100644 --- a/src/View/Form/EntityContext.php +++ b/src/View/Form/EntityContext.php @@ -17,6 +17,7 @@ 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 @@ public function __construct(Request $request, array $context) { */ 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; } diff --git a/tests/TestCase/View/Form/EntityContextTest.php b/tests/TestCase/View/Form/EntityContextTest.php index c6814d27240..f7e0daaad6a 100644 --- a/tests/TestCase/View/Form/EntityContextTest.php +++ b/tests/TestCase/View/Form/EntityContextTest.php @@ -22,6 +22,12 @@ use Cake\Validation\Validator; use Cake\View\Form\EntityContext; +/** + * Test stub. + */ +class Article extends Entity { +} + /** * Entity context test case. */ @@ -44,6 +50,29 @@ public function setUp() { $this->request = new Request(); } +/** + * 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. *