Pregunta

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.

¿Fue útil?

Solución

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.

Otros consejos

I've been using it for a few hours, and in my understanding, zf1 subforms funcionalities are solved in zf2 by using nested fieldsets.

\Zend\Form\Fieldset is also the parent class of \Zend\Form\Form.

The previous answer seems correct to me, but if you prefer to keep forms and subforms in separate classes, read this:

http://zf2.readthedocs.org/en/latest/modules/zend.form.collections.html

Ignore the entity and hydration stuff if you are not interested for now, and look at CreateProduct class, it's a form that uses the FieldSet ProductFieldset as a subform. At rendering time, subform fields will be named like

<input ...name="product[el1]" ... >

(where product is the name of the subform). And $form->getData() will return

array('product'=>array(...))

Note: you need to call $form->prepare(); before rendering, or the nesting won't be processed.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top