Skip to content

Commit

Permalink
[Form] CollectionField::setData() should remove old fields missing fr…
Browse files Browse the repository at this point in the history
…om new data
  • Loading branch information
Jeremy Mikola committed Sep 9, 2010
1 parent 9f5469f commit 9be7cbb
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/Symfony/Component/Form/CollectionField.php
Expand Up @@ -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);
Expand Down
25 changes: 25 additions & 0 deletions tests/Symfony/Tests/Component/Form/CollectionFieldTest.php
Expand Up @@ -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()
Expand Down

0 comments on commit 9be7cbb

Please sign in to comment.