diff --git a/src/View/Form/EntityContext.php b/src/View/Form/EntityContext.php index b2f6073c07b..66f13daa9fd 100644 --- a/src/View/Form/EntityContext.php +++ b/src/View/Form/EntityContext.php @@ -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); @@ -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; @@ -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) { @@ -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); @@ -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)); diff --git a/tests/TestCase/View/Form/EntityContextTest.php b/tests/TestCase/View/Form/EntityContextTest.php index ff876c22333..65fef2ecc57 100644 --- a/tests/TestCase/View/Form/EntityContextTest.php +++ b/tests/TestCase/View/Form/EntityContextTest.php @@ -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. *