2012-10-18 25 views
17

我的表單中有一個名爲* sub_choice *的選擇字段類型,它的選擇將通過AJAX動態加載,具體取決於父選擇字段的名稱* parent_choice *的選定值。加載選項完美無缺,但在提交時驗證sub_choice的值時遇到問題。它提供了「此值無效」驗證錯誤,因爲提交的值在構建時不在sub_choice字段的選項中。那麼有沒有一種方法可以正確驗證sub_choice字段的提交值?以下是構建表單的代碼。我正在使用Symfony 2.1。在Symfony 2中驗證動態加載的選擇

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder->add('parent_choice', 'entity', array(
        'label' => 'Parent Choice', 
        'class' => 'Acme\TestBundle\Entity\ParentChoice' 
    )); 

    $builder->add('sub_choice', 'choice', array(
        'label' => 'Sub Choice', 
        'choices' => array(), 
        'virtual' => true 
    )); 
} 
+0

你有沒有這個運氣?我堅持類似的東西。 –

+0

一個更近的類似的問題鏈接到這一個,其中一個答案看起來不錯,與使用PRE_BIND事件來挑選有效的選項列表:http://stackoverflow.com/questions/18207476/symfony2-動態表單選擇驗證,刪除 – frumious

+0

這裏版本任意值接受 http://stackoverflow.com/questions/28245027/symfony-2-choice-ajax-validation-fix –

回答

-3

假設你有id的子選擇權嗎? 創建並配備一定數量值的空數組並因爲在你的配置它的驗證你不把它作爲一個選擇

$indexedArray = []; for ($i=0; $i<999; $i++){ $indexedArray[$i]= ''; }

然後'choices' => $indexedArray, :)

-2

而且不能建立sub_choice驗證t知道哪些值是有效的(值取決於parent_choice的值)。

您可以做的是在您的控制器中新建YourFormType()之前將parent_choice解析爲實體。 然後,您可以獲得sub_choice的所有可能值,並通過窗體構造函數 - 新YourFormType($ subChoice)提供它們。

在YourFormType你必須添加__construct方法像這樣的:

/** 
* @var array 
*/ 
protected $subChoice = array(); 

public function __construct(array $subChoice) 
{ 
    $this->subChoice = $subChoice; 
} 

,並在表單中添加使用提供值:

$builder->add('sub_choice', 'choice', array(
       'label' => 'Sub Choice', 
       'choices' => $this->subChoice, 
       'virtual' => true 
)); 
18

要你需要前覆蓋sub_choice場的伎倆提交表格:

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    ... 

    $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) { 
     $parentChoice = $event->getData(); 
     $subChoices = $this->getValidChoicesFor($parentChoice); 

     $event->getForm()->add('sub_choice', 'choice', [ 
      'label' => 'Sub Choice', 
      'choices' => $subChoices, 
     ]); 
    }); 
} 
+1

我想這個答案最完全直接地給出了問題所需的內容:依賴於另一個選定值設置的選項,而不必亂七八糟地提供所有選項來通過驗證,然後稍後重新設置選項。這讓我感覺「適當的Symfony 2」解決方案。 – frumious

2

此接受任何值

$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) { 
    $data = $event->getData(); 
    if(is_array($data['tags']))$data=array_flip($data['tags']); 
    else $data = array(); 
    $event->getForm()->add('tags', 'tag', [ 
     'label' => 'Sub Choice', 
     'choices' => $data, 
     'mapped'=>false, 
     'required'=>false, 
     'multiple'=>true, 
    ]); 
});