Symfony表格如何在孩子上自动设置父母

Ale*_*anz 5 php doctrine symfony doctrine-orm

在我的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));
Run Code Online (Sandbox Code Playgroud)

当我尝试保存表格以预先处理孩子并设置父母时,是否有办法避免这种情况.

    $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();
Run Code Online (Sandbox Code Playgroud)

这是来自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>
Run Code Online (Sandbox Code Playgroud)

这是来自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>
Run Code Online (Sandbox Code Playgroud)

tux*_*one 7

除了Koalabaerchen的回答之外,为了让handleRequest在父实体上调用addChild方法,你应该将by_reference设置为false(参见文档):

// ParentFormType
$builder->add('children', 'collection', array(
    ...
    'by_reference' => false,
));
Run Code Online (Sandbox Code Playgroud)


Koa*_*hen 2

在父实体的设置器中,您可以执行类似的操作

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

        return $this;
    }
Run Code Online (Sandbox Code Playgroud)

现在,每次您向实体添加一个子实体(这发生在集合中)时,它也会在子实体中设置父实体。