Skip to content

Commit

Permalink
Add classname reflection to get table names when argument is omitted.
Browse files Browse the repository at this point in the history
  • Loading branch information
markstory committed Feb 5, 2014
1 parent d90abb8 commit 2a87be0
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/View/Form/EntityContext.php
Expand Up @@ -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;

Expand Down Expand Up @@ -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;
}
Expand Down
29 changes: 29 additions & 0 deletions tests/TestCase/View/Form/EntityContextTest.php
Expand Up @@ -22,6 +22,12 @@
use Cake\Validation\Validator;
use Cake\View\Form\EntityContext;

/**
* Test stub.
*/
class Article extends Entity {
}

/**
* Entity context test case.
*/
Expand All @@ -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.
*
Expand Down

0 comments on commit 2a87be0

Please sign in to comment.