Skip to content

Commit e695fe4

Browse files
committed
Use concrete entities on missing data.
When an association is undefined return a concrete entity class. This is necessary as notEmpty/allowEmpty callbacks could reference the entity provider. Refs #5190
1 parent 3f4e79d commit e695fe4

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

src/View/Form/EntityContext.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,8 @@ protected function _getEntity($path) {
268268
$isLast = ($i === $last);
269269

270270
if (!$isLast && $next === null && $prop !== '_ids') {
271-
return new Entity();
271+
$table = $this->_getTable($path);
272+
return $table->newEntity();
272273
}
273274

274275
$isTraversable = (

tests/TestCase/View/Form/EntityContextTest.php

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,15 @@
2929
* Test stub.
3030
*/
3131
class Article extends Entity {
32+
33+
/**
34+
* Testing stub method.
35+
*
36+
* @return bool
37+
*/
38+
public function isRequired() {
39+
return true;
40+
}
3241
}
3342

3443
/**
@@ -647,6 +656,37 @@ public function testIsRequiredAssociatedHasMany() {
647656
$this->assertFalse($context->isRequired(''));
648657
}
649658

659+
/**
660+
* Test isRequired on associated entities with custom validators.
661+
*
662+
* Ensures that missing associations use the correct entity class
663+
* so provider methods work correctly.
664+
*
665+
* @return void
666+
*/
667+
public function testIsRequiredAssociatedCustomValidator() {
668+
$this->_setupTables();
669+
$users = TableRegistry::get('Users');
670+
$articles = TableRegistry::get('Articles');
671+
672+
$validator = $articles->validator();
673+
$validator->notEmpty('title', 'nope', function ($context) {
674+
return $context['providers']['entity']->isRequired();
675+
});
676+
$articles->validator('default', $validator);
677+
678+
$row = new Entity([
679+
'username' => 'mark'
680+
]);
681+
$context = new EntityContext($this->request, [
682+
'entity' => $row,
683+
'table' => 'Users',
684+
'validator' => 'default',
685+
]);
686+
687+
$this->assertTrue($context->isRequired('articles.0.title'));
688+
}
689+
650690
/**
651691
* Test isRequired on associated entities.
652692
*
@@ -943,6 +983,7 @@ protected function _setupTables() {
943983
$articles = TableRegistry::get('Articles');
944984
$articles->belongsTo('Users');
945985
$articles->hasMany('Comments');
986+
$articles->entityClass(__NAMESPACE__ . '\Article');
946987

947988
$comments = TableRegistry::get('Comments');
948989
$users = TableRegistry::get('Users');

0 commit comments

Comments
 (0)