Note that there are some explanatory texts on larger screens.

plurals
  1. POZF2 populate form collections element with child objects
    text
    copied!<p>Based on the Zend Framework 2 manual (<a href="http://framework.zend.com/manual/2.2/en/modules/zend.form.collections.html" rel="nofollow">here</a>) I made a form like this:</p> <pre><code>class ParentForm extends Form { public function init() { $this-&gt;setName('parent_form') -&gt;setAttribute('method', 'post') -&gt;setHydrator(new ClassMethods(true)) -&gt;setInputFilter(new InputFilter()); $this-&gt;add(array( 'type' =&gt; 'Application\Form\Fieldset\Parent', 'name' =&gt; 'parent', 'options' =&gt; array( 'label' =&gt; 'Parent', 'use_as_base_fieldset' =&gt; true ) )); $this-&gt;add(array( 'type' =&gt; 'Zend\Form\Element\Csrf', 'name' =&gt; 'csrf' )); $this-&gt;add(array( 'name' =&gt; 'submit', 'attributes' =&gt; array( 'type' =&gt; 'submit', 'value' =&gt; 'Send' ) )); } } </code></pre> <p>And the 'parent' fieldset:</p> <pre><code>class ParentFieldset extends Fieldset { protected $count = 2; public function init() { $this-&gt;setName('parent_fieldset') -&gt;setHydrator(new ClassMethodsHydrator(false)) -&gt;setObject(new Model\Parent()); $this-&gt;add(array('type' =&gt; 'Element\MyField')); $this-&gt;add(array( 'type' =&gt; 'collection', 'name' =&gt; 'children', 'options' =&gt; array( 'label' =&gt; 'Children', 'count' =&gt; $this-&gt;count, 'should_create_template' =&gt; true, 'allow_add' =&gt; true, 'target_element' =&gt; array( 'type' =&gt; 'Application\Form\Fieldset\Child', 'name' =&gt; 'child', 'options' =&gt; array( 'label' =&gt; child', ), ), ) )); } public function setCount($count) { $this-&gt;count = max($count, 2); } } </code></pre> <p>This works great to hydrate my Parent object with data obtained from my form. A var_dump of the resuting object will look like:</p> <pre><code>object(Parent) public myField =&gt; foo public children =&gt; array =&gt; 0 =&gt; object(Child) public field1 =&gt; value1 public field2 =&gt; value2 .... 1 =&gt; object(Child) ..... 2 =&gt; object(Child) ..... </code></pre> <p>But I cannot figure out how to populate this multi-dimensional form with the above object if hydrated from the database (for editing purposes). How can I do that?</p> <p>Note: the count property in the form is set to the same number of children as in the object.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload