2017-04-14 53 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是關鍵。