Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony Form howto automaticly set parent on child

On my formType I added another subform

    // 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 to foreach the childs 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 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 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>
like image 871
Alexander Schranz Avatar asked Jan 21 '15 08:01

Alexander Schranz


2 Answers

In addition to Koalabaerchen's answer, in order to let handleRequest call the addChild method on the parent entity you should set by_reference to false (see documentation):

// ParentFormType
$builder->add('children', 'collection', array(
    ...
    'by_reference' => false,
));
like image 109
tuxone Avatar answered Oct 13 '22 10:10

tuxone


In the setter in the entity of the parent you can do something like

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

        return $this;
    }

Now everytime you add a child to the entity (which happens with the collection) it also sets the parent inside the child.

like image 44
Koalabaerchen Avatar answered Oct 13 '22 10:10

Koalabaerchen