diff --git a/src/Symfony/Component/Form/CollectionField.php b/src/Symfony/Component/Form/CollectionField.php index f982bd64abd7..70095b9d18e4 100644 --- a/src/Symfony/Component/Form/CollectionField.php +++ b/src/Symfony/Component/Form/CollectionField.php @@ -55,8 +55,10 @@ public function setData($collection) throw new UnexpectedTypeException('The data must be an array'); } - foreach ($collection as $name => $value) { - $this->add($this->newField($name, $name)); + foreach ($this as $name => $field) { + if (!$this->getOption('modifiable') || $name != '$$key$$') { + $this->remove($name); + } } parent::setData($collection); diff --git a/tests/Symfony/Tests/Component/Form/CollectionFieldTest.php b/tests/Symfony/Tests/Component/Form/CollectionFieldTest.php index 91fde3b682be..9a01a4d594ee 100644 --- a/tests/Symfony/Tests/Component/Form/CollectionFieldTest.php +++ b/tests/Symfony/Tests/Component/Form/CollectionFieldTest.php @@ -27,6 +27,31 @@ public function testSetDataAdjustsSize() $this->assertEquals(2, count($field)); $this->assertEquals('foo@foo.com', $field[0]->getData()); $this->assertEquals('foo@bar.com', $field[1]->getData()); + + $field->setData(array('foo@baz.com')); + $this->assertTrue($field[0] instanceof TestField); + $this->assertFalse(isset($field[1])); + $this->assertEquals(1, count($field)); + $this->assertEquals('foo@baz.com', $field[0]->getData()); + } + + public function testSetDataAdjustsSizeIfModifiable() + { + $field = new CollectionField(new TestField('emails'), array( + 'modifiable' => true, + )); + $field->setData(array('foo@foo.com', 'foo@bar.com')); + + $this->assertTrue($field[0] instanceof TestField); + $this->assertTrue($field[1] instanceof TestField); + $this->assertTrue($field['$$key$$'] instanceof TestField); + $this->assertEquals(3, count($field)); + + $field->setData(array('foo@baz.com')); + $this->assertTrue($field[0] instanceof TestField); + $this->assertFalse(isset($field[1])); + $this->assertTrue($field['$$key$$'] instanceof TestField); + $this->assertEquals(2, count($field)); } public function testThrowsExceptionIfObjectIsNotTraversable()