Symfony Form howto automatically sets parent to child

In my type, I added another subformation

    // ParentFormType
    $builder->add('children', 'collection', array(
        'type' => new ChildFormType(),
        'prototype'    => true,
        'allow_delete' => true,
        'allow_add' => true,
    ));

    // ChildFormType
    $builder->add('age', 'text', array(
        'required' => true));

When I try to save the form in order to select the children and set the parent, is there a way to avoid this foreach .

    $em = $this->get('doctrine.orm.entity_manager');
    /** This foreach I want to avoid */
    foreach ($parent->getChildren() as $child) {
        $child->setParent($parent);
    }
    $em->persist($parent);
    $em->flush();

Here is the ORM-XML from the parent:

    <one-to-many field="children" target-entity="Client\Bundle\WebsiteBundle\Entity\Children" mapped-by="parent">
        <cascade>
            <cascade-persist />
        </cascade>
    </one-to-many>

Here is the ORM-XML from the parent:

    <many-to-one field="parent" target-entity="Client\Bundle\WebsiteBundle\Entity\Parent" inversed-by="children">
        <join-columns>
            <join-column name="idParents" referenced-column-name="id" on-delete="CASCADE" nullable="false" />
        </join-columns>
    </many-to-one>
+4
source share
2 answers

In addition to Koalabaerchen's answer, for handleRequest to call the addChild method on the parent object, you must set by_reference to false (see the documentation ):

// ParentFormType
$builder->add('children', 'collection', array(
    ...
    'by_reference' => false,
));
+6
source

-

 public function addChild(Child $children)
    {
        $this->children->add($children);
        $children->setParent($this);

        return $this;
    }

, ( ), .

+2

All Articles