同一实体的多行以单一形式

Multiple rows from the same entity in single form

我有一个 Doctrine 扩展 tree Entity which I want to put entirely (or only a node and all its children) in a form. That is, I want to be able to modify the entire (sub)tree in a single form. I have taken a look at “multiple rows in form for the same entity in symfony2,”但是,我无法将它应用到 Symfony3 中包含所有子节点的树上。

我在想像这样的控制器

$repository = $this->getDoctrine()->getRepository('AppBundle:Category');
$tree = $repository->children(null, true);

$form = $this->createForm(CategoryType::class, $tree);

还有一个CategoryType喜欢

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('title');
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => Category::class /* or should it be `null`? */,
    ));
}

使用以下控制器:

public function editAction(Request $request)
{
    $repository = $this->getDoctrine()->getRepository('AppBundle:Category');
    $categories = $repository->children(null, false); // get the entire tree including all descendants

    $form = $this->createFormBuilder(array('categories' => $categories));
    $form->add('categories', CollectionType::class, array(
        'entry_type' => CategoryType::class,
    ));
    $form->add('edit', SubmitType::class);

    $form = $form->getForm();
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $data = $form->getData();

        // $data['categories'] contains an array of AppBundle\Entity\Category
        // use it to persist the categories in a foreach loop
    }

    return $this->render(...)
}

CategoryType 就像“正常”一样,例如我问题中的那个。

使用 array('categories' => $categories) 创建表单构建器并添加一个名为 categories.

的表单 CollectionType 字段是关键