ZF-10411: Form element doesn't work after it was added with Zend_Form_DisplayGroup::addElement()

Description

Here is an example: We have form A and form B A inherited from B, B inherited from Zend_Form. Form B defines some element and adds it to display group. Form A also defines an element and adds it to display group, defined in form B with Zend_Form_DisplayGroup::addElement() method.

In this case element from form A will be rendered in form properly, but will not work as should - populate and getValue(s) doesn't work for it.

If to add element in form A to the form with Zend_Form::addElement() (not just to display group) it will rendered twice - inside groups and outside of it and became to work.

Code example


class Form_Bform extends App_Form
{
    public function init()
    {
        $this->addElement(
            'text',
            'el1',
            array(
                'label' => 'Title',
                'required' => true,
            )
        );


        $this->addDisplayGroup(array('el1'), 'group1', array('legend'=>'legend 1'));
    }
}


class Form_Aform extends Form_Bform
{
    public function init()
    {
        parent::init();
        $element = new Zend_Form_Element_Text('el2', array(
            'label' => 'Customer type',
            )
        );

        //Uncomment the following line and element will be added twice
        //$this->addElement($element);
        $this->group1->addElement($element);
    }
}

Comments

Element MUST be attached to a form or subform; attaching them ONLY to a DisplayGroup means they will never be rendered. In other words, you need to attach the element to the display group after it is already attached to the form.

In your Form A example, you should be adding the element to the form using $this->addElement(), and then adding it by name to the display group:


class Form_Aform extends Form_Bform
{
    public function init()
    {
        parent::init();
        $element = new Zend_Form_Element_Text('el2', array(
            'label' => 'Customer type',
        ));
        $this->addElement($element);

        // OR:
        $this->addElement('text', 'el2', array(
            'label' => 'Customer type',
        ));

        // Add to group:
        $this->group1->addElement($this->el2);
    }
}

Did you miss this?


        //Uncomment the following line and element will be added twice
        //$this->addElement($element);
        $this->group1->addElement($element);

Your code renders "el2" field two times - inside and outside of fieldset

I did indeed miss that, and I've verified the issue.

Oddly, addDisplayGroup() uses the exact same methodology for adding elements as simply calling addElement(); this is going to take some debugging to properly diagnose.

Fixed in r22930; will release with next minor release (1.11) as it involved adding new methods.