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>
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,
));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With