Search code examples
zend-frameworkzend-formzend-form-sub-form

subform within a subform


I'm working on a model using Zend Form. I have a subform called $product_item. I would like to add multiple instances of it to another subform called $items. How would I go about doing that? I'm not finding the Zend reference guide particularly helpful.


Solution

  • You can just add sub-forms to sub-forms:-

    $form = new Application_Form_Test();
    $subForm1 = new Application_Form_TestSubForm();
    $subForm2 = new Application_Form_TestSubForm();
    $subForm1->addSubForm($subForm2, 'sub2');
    $form->addSubForm($subForm1, 'sub1');
    $this->view->form = $form;
    

    On submission the subform values will be available in arrays in the $_POST array. $value=$_POST['sub1']['sub2']['name'] for example.

    http://framework.zend.com/manual/en/zend.form.forms.html#zend.form.forms.subforms

    To print or access elements in sub forms you have several options:-

    If $subForm1 has an element declared thus:-

    $email = new Zend_Form_Element_Text('email');
    

    Then the email field can be rendered in the view like this:-

    <?php echo $this->element->sub1->email; ?>
    

    Remember that the elements are referenced by their names not by the variables you use to declare them.

    Also, remember that $this->element is referencing an instance of Zend_Form so you have all of those methods available. That means you can do this:-

    <?php
        $form = $this->element;
        $formElements = $form->getElements();
    ?>