Skip to content
This repository was archived by the owner on Jan 30, 2020. It is now read-only.

Commit bfd7ce3

Browse files
committed
Fix collection hydration problem
1 parent 767ed40 commit bfd7ce3

File tree

2 files changed

+46
-4
lines changed

2 files changed

+46
-4
lines changed

src/Fieldset.php

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
use Traversable;
1313
use Zend\Code\Reflection\ClassReflection;
14+
use Zend\Form\Element\Collection;
1415
use Zend\Hydrator;
1516
use Zend\Hydrator\HydratorAwareInterface;
1617
use Zend\Hydrator\HydratorInterface;
@@ -564,12 +565,18 @@ public function bindValues(array $values = [])
564565
$hydrator = $this->getHydrator();
565566
$hydratableData = [];
566567

567-
foreach ($values as $name => $value) {
568-
if (!$this->has($name)) {
569-
continue;
568+
foreach ($this->iterator as $element) {
569+
$name = $element->getName();
570+
571+
if (!array_key_exists($name, $values)) {
572+
if (!($element instanceof Collection)) {
573+
continue;
574+
}
575+
576+
$values[$name] = [];
570577
}
571578

572-
$element = $this->iterator->get($name);
579+
$value = $values[$name];
573580

574581
if ($element instanceof FieldsetInterface && $element->allowValueBinding()) {
575582
$value = $element->bindValues($value);

test/FormTest.php

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2135,4 +2135,39 @@ public function testSetValidationGroupOnFormWithNestedCollectionsPopulatesOnlyFi
21352135

21362136
$this->assertEquals($data, $this->form->getData());
21372137
}
2138+
2139+
public function testShouldHydrateEmptyCollection()
2140+
{
2141+
$fieldset = new Fieldset('example');
2142+
$fieldset->add([
2143+
'type' => 'Zend\Form\Element\Collection',
2144+
'name' => 'foo',
2145+
'options' => [
2146+
'label' => 'InputFilterProviderFieldset',
2147+
'count' => 1,
2148+
'target_element' => [
2149+
'type' => 'text'
2150+
]
2151+
],
2152+
]);
2153+
2154+
$this->form->add($fieldset);
2155+
$this->form->setBaseFieldset($fieldset);
2156+
$this->form->setHydrator(new \Zend\Hydrator\ObjectProperty());
2157+
2158+
$object = new Entity\SimplePublicProperty();
2159+
$object->foo = ['item 1', 'item 2'];
2160+
2161+
$this->form->bind($object);
2162+
2163+
$this->form->setData([
2164+
'submit' => 'Confirm',
2165+
'example' => [
2166+
//'foo' => [] // $_POST does't have this if collection is empty
2167+
]
2168+
]);
2169+
2170+
$this->assertTrue($this->form->isValid());
2171+
$this->assertEquals([], $this->form->getObject()->foo);
2172+
}
21382173
}

0 commit comments

Comments
 (0)