Browse Source

Merge pull request #4803 from cakephp/issue-form-helper-error

Fix incorrect entity being used for missing indexes.
José Lorenzo Rodríguez 11 years ago
parent
commit
b1ca01ddaf
2 changed files with 68 additions and 1 deletions
  1. 1 1
      src/View/Form/EntityContext.php
  2. 67 0
      tests/TestCase/View/Form/EntityContextTest.php

+ 1 - 1
src/View/Form/EntityContext.php

@@ -267,7 +267,7 @@ class EntityContext implements ContextInterface {
 			$next = $this->_getProp($entity, $prop);
 
 			if ($next === null && $prop !== '_ids') {
-				return false;
+				return new Entity();
 			}
 
 			$isLast = ($i === $last && isset($next));

+ 67 - 0
tests/TestCase/View/Form/EntityContextTest.php

@@ -649,6 +649,42 @@ class EntityContextTest extends TestCase {
 	}
 
 /**
+ * Test isRequired on associated entities.
+ *
+ * @return void
+ */
+	public function testIsRequiredAssociatedHasManyMissingObject() {
+		$this->_setupTables();
+
+		$comments = TableRegistry::get('Comments');
+		$validator = $comments->validator();
+		$validator->allowEmpty('comment', function ($context) {
+			return $context['providers']['entity']->isNew();
+		});
+
+		$row = new Article([
+			'title' => 'My title',
+			'comments' => [
+				new Entity(['comment' => 'First comment'], ['markNew' => false]),
+			]
+		]);
+		$context = new EntityContext($this->request, [
+			'entity' => $row,
+			'table' => 'Articles',
+			'validator' => 'default',
+		]);
+
+		$this->assertTrue(
+			$context->isRequired('comments.0.comment'),
+			'comment is required as object is not new'
+		);
+		$this->assertFalse(
+			$context->isRequired('comments.1.comment'),
+			'comment is not required as missing object is "new"'
+		);
+	}
+
+/**
  * Test isRequired on associated entities with custom validators.
  *
  * @return void
@@ -865,6 +901,37 @@ class EntityContextTest extends TestCase {
 	}
 
 /**
+ * Test error on associated entities.
+ *
+ * @return void
+ */
+	public function testErrorAssociatedHasMany() {
+		$this->_setupTables();
+
+		$comments = TableRegistry::get('Comments');
+		$row = new Article([
+			'title' => 'My title',
+			'comments' => [
+				new Entity(['comment' => '']),
+				new Entity(['comment' => 'Second comment']),
+			]
+		]);
+		$row->comments[0]->errors('comment', ['Is required']);
+		$context = new EntityContext($this->request, [
+			'entity' => $row,
+			'table' => 'Articles',
+			'validator' => 'default',
+		]);
+
+		$this->assertEquals([], $context->error('title'));
+		$this->assertEquals([], $context->error('comments.0.user_id'));
+		$this->assertEquals([], $context->error('comments.0'));
+		$this->assertEquals(['Is required'], $context->error('comments.0.comment'));
+		$this->assertEquals([], $context->error('comments.1'));
+		$this->assertEquals([], $context->error('comments.1.comment'));
+	}
+
+/**
  * Setup tables for tests.
  *
  * @return void