2015-09-17 31 views
5

我使用表單組件並在呈現爲選擇字段的表單上有一個choice Field Type。 在客戶端,我使用select2 plugin初始化選擇與設置tags: true允許添加一個新的值。 但是,如果我添加一個新值,那麼服務器上的驗證將失敗,並顯示錯誤允許在選項中添加新值字段類型

該值無效。

因爲新值不在選擇列表中。

有沒有辦法允許添加一個新值來選擇字段類型?

回答

12

問題出在選擇變換器,它會擦除​​選擇列表中不存在的值。
The workaround with disabling the transformer幫我:

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder->add('choiceField', 'choice', ['choices' => $someList]); 

    // more fields... 

    $builder->get('choiceField')->resetViewTransformers(); 
} 
+0

不適用於展開=> true –

1

不,沒有。使用選擇2事件來創建通過AJAX的新選擇

  • 驗證表單之前捕捉髮布選項

    • ,並將其添加到選項列表
    • 您應該手動要麼實現此

  • 3

    這裏是萬一有人需要這樣的的EntityType而不是ChoiceType的示例代碼。將此添加到您的表單類型中:

    use AppBundle\Entity\Category; 
    use Symfony\Component\Form\FormEvent; 
    use Symfony\Component\Form\FormEvents; 
    
    $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) { 
        $data = $event->getData(); 
    
        if (!$data) { 
         return; 
        } 
    
        $categoryId = $data['category']; 
    
        // Do nothing if the category with the given ID exists 
        if ($this->em->getRepository(Category::class)->find($categoryId)) { 
         return; 
        } 
    
        // Create the new category 
        $category = new Category(); 
        $category->setName($categoryId); 
        $this->em->persist($category); 
        $this->em->flush(); 
    
        $data['category'] = $category->getId(); 
        $event->setData($data); 
    }); 
    
    相關問題