ZF-9666: Forms with SubForms Having Elements with Same Names Populate Incorrectly

Description

The following code:

$form = new Zend_Form; $form->addElement('text', 'foo'); $subForm = new Zend_Form_SubForm; $subForm->addElement('text', 'foo'); $form->addSubForm($subForm, 'mySubForm'); $form->populate(array('foo' => 'bar')); echo $form;

Renders as:

 
 
 

The sub form's 'foo' should not be populated with 'bar'.

Comments

This patch fixes the issue, unit test included


Index: tests/Zend/Form/FormTest.php
===================================================================
--- tests/Zend/Form/FormTest.php        (Revision 21845)
+++ tests/Zend/Form/FormTest.php        (Arbeitskopie)
@@ -1184,6 +1184,21 @@
         $this->assertTrue($this->form->isValid($data));
     }
 
+    /**
+     * @group ZF-9666
+     */
+    public function testSetDefaultsDiscardsPopulatedValues()
+    {
+        $this->form->addElement('text', 'foo');
+        $this->form->addSubForm(new Zend_Form_SubForm(), 'bar')
+                   ->bar->addElement('text', 'foo');
+
+        $this->form->populate(array('foo' => 'foo Value'));
+        $html = $this->form->setView($this->getView())
+                           ->render();
+        $this->assertEquals(1, preg_match_all('/foo Value/', $html, $matches));
+    }
+
     // Sub forms
 
     public function testCanAddAndRetrieveSingleSubForm()
Index: library/Zend/Form.php
===================================================================
--- library/Zend/Form.php       (Revision 21845)
+++ library/Zend/Form.php       (Arbeitskopie)
@@ -1232,6 +1232,7 @@
         foreach ($this->getElements() as $name => $element) {
             if (array_key_exists($name, $defaults)) {
                 $this->setDefault($name, $defaults[$name]);
+                unset($defaults[$name]);
             }
         }
         foreach ($this->getSubForms() as $name => $form) {

    public function testSetDefaultsDiscardsPopulatedValues()
    {
        $this->form->addElement('text', 'foo');
        $this->form->addSubForm(new Zend_Form_SubForm(), 'bar')
                   ->bar->addElement('text', 'foo');

        $this->form->populate(array('foo' => 'foo Value'));
        $html = $this->form->setView($this->getView())
                           ->render();
        $this->assertEquals(1, preg_match_all('/foo Value/', $html, $matches));
    }

This patch appears to solve the problem. Thanks for attending to this so quickly!

This Patch duplicates now Patch #4 of ZF-9607