Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Somehow the information is scattered in the cookbook <a href="http://symfony.com/doc/current/cookbook/form/form_collections.html" rel="nofollow">http://symfony.com/doc/current/cookbook/form/form_collections.html</a> under additional note section <em>Doctrine: Cascading Relations and saving the "Inverse" side</em>.</p> <p>This issue impress me so that I put some actual coding/research on it. :)<br> Here is what I found.</p> <p>In the <code>Entity\Branch</code>, tell doctrine to cascade its persist operation on metadata property and modify <code>setMetadata()</code> to set the current branch for each metadata going to be persisted.</p> <pre><code>/** * * @ORM\OneToMany(targetEntity="BranchMeta", mappedBy="branch", cascade={"persist"}) */ private $metadata; public function setMetadata(ArrayCollection $metadata) { foreach ($metadata as $m) { $m-&gt;setBranch($this); } $this-&gt;metadata = $metadata; } </code></pre> <p>In the <code>Form\BranchType</code>, add metadata field with the appropriate option, and of course set the default <code>data_class</code> to <code>Entity\Branch</code> (your <code>BranchType</code> above doesn't have this). In this Form Type, the <code>'by_reference' =&gt; false</code> option is important to ensure that the <code>setMetadata()</code> function is called during persist (<a href="http://symfony.com/doc/current/reference/forms/types/collection.html#by-reference" rel="nofollow">http://symfony.com/doc/current/reference/forms/types/collection.html#by-reference</a>).</p> <pre><code>public function buildForm(FormBuilderInterface $builder, array $options) { $builder-&gt;add('name'); $builder-&gt;add('metadata', 'collection', array( 'type' =&gt; new BranchMetaType(), 'allow_add' =&gt; true, 'by_reference' =&gt; false, )); } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver-&gt;setDefaults( array( 'data_class' =&gt; 'Acme\Bundle\ConsysBundle\Entity\Branch' )); } </code></pre> <p>And, finally try adding some dummy branchmeta in the controller</p> <pre><code>public function newAction() { $entity = new Branch(); $branchmeta1 = new BranchMeta(); $branchmeta1-&gt;setMetaname('dummy meta name #1'); $branchmeta1-&gt;setMetavalue('dummy meta value #1'); $entity-&gt;getMetadata()-&gt;add($branchmeta1); $branchmeta2 = new BranchMeta(); $branchmeta2-&gt;setMetaname('dummy meta name #2'); $branchmeta2-&gt;setMetavalue('dummy meta value #2'); $entity-&gt;getMetadata()-&gt;add($branchmeta2); $form = $this-&gt;createForm(new BranchType(), $entity); return array( 'entity' =&gt; $entity, 'form' =&gt; $form-&gt;createView(), ); } </code></pre>
 

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