在我的formType上我添加了另一个子表单
// 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));
当我尝试将表单保存到fores the childs并设置父级时,是否有办法避免使用此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();
以下是来自Parent的ORM-XML:
<one-to-many field="children" target-entity="Client\Bundle\WebsiteBundle\Entity\Children" mapped-by="parent">
<cascade>
<cascade-persist />
</cascade>
</one-to-many>
以下是来自Parent的ORM-XML:
<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>
答案 0 :(得分:6)
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,
));
答案 1 :(得分:2)
在父级实体的setter中,您可以执行类似
的操作 public function addChild(Child $children)
{
$this->children->add($children);
$children->setParent($this);
return $this;
}
现在,每次向实体添加子项时(与集合一起发生),它也会在子项内部设置父项。