2017-04-14 52 views
2

我有一个Docvine扩展tree Entity,我想完全(或只是一个节点及其所有子节点)放在一个表单中。也就是说,我希望能够以单一形式修改整个(子)树。我看了一下“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`? */, 
    )); 
} 
+0

就像在你连接的答案,你需要有一个形式的集合... http://symfony.com/doc/current/form/form_collections.html – ehymel

+0

@ehymel我明白了,但我怎么避免添加容纳所有孩子的“容器”类别?我只想将一个数组传递给窗体。 – timothymctim

+0

不要回避它。你的“容器”只不过是你的根类“Category”中的一个参数,它包含了子数组。调用该参数'$ categories'并添加适当的getter/setter方法。当然,setter将是'public function addCategory(Category $ category){}'。 – ehymel

回答

1

使用以下控制器:

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)一起创建表单构建器并添加表单CollectionType字段的名称是categories是关键。