Skip to content

Commit

Permalink
Allow retrieving entity from EntityContext.
Browse files Browse the repository at this point in the history
  • Loading branch information
ADmad committed Feb 23, 2015
1 parent 89fd081 commit 1952f85
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
19 changes: 12 additions & 7 deletions src/View/Form/EntityContext.php
Expand Up @@ -213,7 +213,7 @@ public function val($field)
return null;
}
$parts = explode('.', $field);
$entity = $this->_getEntity($parts);
$entity = $this->entity($parts);

if (end($parts) === '_ids' && !empty($entity)) {
return $this->_extractMultiple($entity, $parts);
Expand Down Expand Up @@ -250,12 +250,17 @@ protected function _extractMultiple($values, $path)
* entity. If the path does not contain a leaf entity false
* will be returned.
*
* @param array $path Each one of the parts in a path for a field name
* @return \Cake\DataSource\EntityInterface|bool
* @param array|null $path Each one of the parts in a path for a field name
* or null to get the entity passed in contructor context.
* @return \Cake\DataSource\EntityInterface|\Traversable|array|bool
* @throws \RuntimeException When properties cannot be read.
*/
protected function _getEntity($path)
public function entity($path = null)
{
if ($path === null) {
return $this->_context['entity'];
}

$oneElement = count($path) === 1;
if ($oneElement && $this->_isCollection) {
return false;
Expand Down Expand Up @@ -331,7 +336,7 @@ protected function _getProp($target, $field)
public function isRequired($field)
{
$parts = explode('.', $field);
$entity = $this->_getEntity($parts);
$entity = $this->entity($parts);

$isNew = true;
if ($entity instanceof Entity) {
Expand Down Expand Up @@ -375,7 +380,7 @@ protected function _getValidator($parts)
return !is_numeric($part);
});
$key = implode('.', $keyParts);
$entity = $this->_getEntity($parts) ?: null;
$entity = $this->entity($parts) ?: null;

if (isset($this->_validator[$key])) {
$this->_validator[$key]->provider('entity', $entity);
Expand Down Expand Up @@ -488,7 +493,7 @@ public function hasError($field)
public function error($field)
{
$parts = explode('.', $field);
$entity = $this->_getEntity($parts);
$entity = $this->entity($parts);

if ($entity instanceof Entity) {
return $entity->errors(array_pop($parts));
Expand Down
14 changes: 14 additions & 0 deletions tests/TestCase/View/Form/EntityContextTest.php
Expand Up @@ -66,6 +66,20 @@ public function setUp()
$this->request = new Request();
}

/**
* Test getting entity back from context.
*
* @return void
*/
public function testEntity()
{
$row = new Article();
$context = new EntityContext($this->request, [
'entity' => $row,
]);
$this->assertSame($row, $context->entity());
}

/**
* Test getting primary key data.
*
Expand Down

0 comments on commit 1952f85

Please sign in to comment.