2013-01-15 53 views
9

我有從數據庫實體的選擇字段的表單:如何禁用表單選擇類型中的特定項目?

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder->add('categories', 'document', array(
     'class' => 'Acme\DemoBundle\Document\Category', 
     'property' => 'name', 
     'multiple' => true, 
     'expanded' => true, 
     'empty_value' => false 
    )); 
} 

這種形式會產生複選框列表,將呈現爲:

[ ] Category 1 
[ ] Category 2 
[ ] Category 3 

我想禁用某些項目在這個列表中的價值,但我不知道我應該在哪裏攔截選擇領域項目來做到這一點。

有沒有人知道解決方案?

+0

你想要它們變灰或只是不顯示在第一位嗎? – Squazic

+0

我剛剛發現可以在'finishView'中直觀地禁用它們。仍然澄清如何防止在setData期間更改禁用的值。 –

回答

11

剛處理它與finishViewPRE_BIND事件監聽器。

+0

這幫助我擺脫了困境。謝謝。 – Bogdan

+0

sf 2.3中的某些變化*因爲這個解決方案不適合我。 – Pawel

+2

這是不安全的,因爲(如果html被操縱)選擇仍然是可能的。 – Nemo64

8

您可以使用$form->add()'choice_attr',並通過將據此決定是否增加disabled屬性或不依賴於值,鍵或索引選擇的功能。

... 
    'choice_attr' => function($key, $val, $index) { 
     $disabled = false; 

     // set disabled to true based on the value, key or index of the choice... 

     return $disabled ? ['disabled' => 'disabled'] : []; 
    }, 
... 
+1

這個解決方案有什麼問題?恕我直言,這是正確的方式來做到這一點,請參閱:http://symfony.com/doc/current/reference/forms/types/choice.html#choice-attr –

+0

@DavidKmenta不支持2.7之前版本的Symfony – nomistic

相關問題