zend-framework2subforms

How to use subforms in Zend Framework2


Is there a way how I can use zend subforms in Zend Framework2. When I did a search in the internet I have landed upon many examples showing how to use zend subforms but using Zend Framework1.

In case if somebody has a link/example where one can go through a basic example, would be great.

Any information is appreciated.


Solution

  • Because Zend\Form is tree structure, you could add another form into your form with a form name. Such like this:

    $form = new \Zend\Form\Form();
    $form->add(array(
        'name' => 'username',
        'type'  => 'Zend\Form\Element\Text',
    ));
    
    $subForm = new \Zend\Form\Form();
    $subForm->setName('subform');
    $subForm->add(array(
        'name' => 'email',
        'type'  => 'Zend\Form\Element\Text',
    ));
    
    $form->add($subForm);
    
    $form->prepare();
    
    $helper = new Zend\Form\View\Helper\FormText();
    echo $helper($form->get('username')); //<input type="text" name="username" value="">
    echo $helper($form->get('subform')->get('email')); //<input type="text" name="subform[email]" value="">
    

    Notice that the "subform" input name will be add form name as prefix automatic.