2017-02-09 98 views
0

我在symfony,User和Tags中有2个实体,每个用户都与许多标签有关系。Symfony窗​​体,新实体和实体类型的集合

在我的用户表单中,我希望能够选择一个或多个标签并创建新标签。

我该如何做到这一点?

我读过如何选择一个标签或创建一个新标签,但这不是我想要的。

回答

0

选择1个或更多的心不是太硬:见 http://symfony.com/doc/current/reference/forms/types/collection.html

具体使用allow_addallow_deleteprototype选项。

$builder->add('favorite_cities', CollectionType::class, array(
    'entry_type' => EntityType::class, 
    'entry_options' => array(
     'prototype' => true, 
     'allow_add' => true, 
     'allow_delete' => true, 
     'class' => 'AppBundle:Tag' 
    ), 
)); 

这将允许您添加和删除存在的标签,在相同的上下文中创建标签有点棘手。你可以做的是不使用标签实体直接使用标准输入字段,然后在你的控制器循环中,检查标签是否存在并将其关联,如果它没有创建它。喜欢的东西:

// AppBundle/Form/UserType.php 
... 
$builder->add('favorite_cities', CollectionType::class, array(
    'entry_type' => TextType::class, 
    'entry_options' => array(
     'prototype' => true, 
     'allow_add' => true, 
     'allow_delete' => true, 
    ), 
)); 

// AppBundle/Controller/UserController 
... 
public function addFavoriteCitiesAction(Request $request) { 
    $user = ... // However you get your user 
    $form = $this->createForm(UserType::class,$user); 

    if($request->isMethod('POST')) { 
     $form->handleRequest($request); 

     $favCities = $user->getFavoriteCities(); // Should be an array of strings 
     $em = $this->getDoctrine()->getManager(); 
     $tagRepo = $em->getRepository('AppBundle:Tag'); 
     foreach($favCities as $favCity) { 
      $tag = $tagRepo->findOneBy([ 
       'name' => $favCity 
      ]); 
      if(!$tag){ 
       $tag = new Tag(); // AppBundle/Entity/Tag.php ? 
       $tag->setName($favCity); 
       $em->persist($tag); 
      } 
      $user->addTag($tag); 
     } 
     $em->flush(); 
    } 
    return [ 
     'form' => $form->createView(); 
    ]; 

} 

此代码处理不当经过测试,更意在显示和榜样,我假设一下自己的设置,但像它应该为你工作。

+0

好吧,这是一个可能的解决方案,但不是我正在寻找的。我想维护我的标签类型,因为有很多字段和其他关系。 –

+0

@RiccardoCorrò你是什么TagsType看起来像?也许这可以适应它呢? – Chausser

+0

是的,它可以。但它可能会使管理复杂化,我可能会失去symfony形式的效率。 –