2013-08-18 56 views
2

我有一個類型爲「choice」的窗體小部件,它顯示爲許多複選框的列表。一切都很好。所以強調一下:有一個小部件,有許多複選框(而不是幾個複選框小部件)。在buildForm()中禁用選擇小部件的一些複選框

現在,我想禁用其中一些複選框。這些數據在$ options-Array中是可用的。

這裏是buildForm() - 我FooType.php的功能

... 
public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
    ->add('foo', 'choice', array('choices' => $options['choiceArray']['id'], 
     'multiple' => true, 
     'expanded' => true, 
     'disabled' => $options['choiceArray']['disabled'] // does not work (needs a boolean) 
     'data'  => $options['choiceArray']['checked'], // works 
     'attr'  => array('class' => 'checkbox'))) 
    ; 
} 
... 

我的枝條,模板看起來是這樣的:

{% for foo in fooForm %} 

    <dd>{{ form_widget(foo) }}</dd> 

{% endfor %} 

我只能禁用所有複選框(通過設置'禁用'=>在buildForm中爲true)。並傳遞一個數組不起作用(如片段中所述)。

如何禁用我選擇的小部件中的一些選中的複選框(存儲在$ options ['choiceArray'] ['disabled']中)?

+3

Symfony EventSubscriber可以幫助你http://stackoverflow.com/questions/12642473/symfony2-checkbox-choice-field-disable-one-checkbox –

+0

@Milos:感謝您的有用評論!使用EventSubscriber似乎是解決方案,但是......實施起來非常複雜。由於我是一個Symfony2新手,我真的很感激一些幫助。預先感謝任何進一步的提示和片段! [Symfony2 Dynamic Forms](http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html) – squirrel

+0

如果您想根據對象中的當前值確定禁用哪些選項,則EventSubscriber僅與相關。它不會幫助您設置各個選項元素的屬性。這是一個普遍的要求,沒有簡單的解決方案。您需要製作您的表單選擇對象或提供您自己的樹枝模板。這兩種解決方案都不容易,我也不知道任何好的例子。 JavaScript可能是您最好的選擇。 – Cerad

回答

1

我已經解決了使用JQuery的問題。

  • 在我的FooType.php我stringify字段應該被禁用的數組。
  • 我通過該字符串在buildForm() - 經由一個隱藏字段函數到模板
  • 有我使用JQuery再次分割字符串到ID和過程禁用複選框和變灰標籤

這裏是PHP碼(FooType.php):

... 
public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $disabledCount = sizeof($options['choiceArray']['disabled']); 
    $disabledString = ''; 

    for ($i = 0; $i < $disabledCount; $i++) 
    { 
     $disabledString .= $options['choiceArray']['disabled'][$i]; 

     if ($i < $disabledCount-1) 
     { 
      $disabledString .= '|'; 
     } 
    } 



    $builder 
     ->add('foo', 'choice', array('choices' => $options['choiceArray']['id'], 
               'multiple' => true, 
               'expanded' => true, 
               'data'  => $options['choiceArray']['checked'], 
               'attr'  => array('class' => 'checkbox'))) 
     ->add('foo_disabled', 'hidden', array('data' => $disabledString)) 
    ; 
} 
... 

這裏是JavaScript部分(小枝模板):

function disableModule() 
{ 
    var disabledString = $('#foo_disabled').val(); 

    var disabledArray = disabledString.split('|'); 

    $.each(disabledArray, function(disKey, disVal) 
    { 
     // deactivate checkboxes 
     $('input[id="'+idCurrent+'"]').attr("disabled", true); 

     // grey out label for checkboxes 
     $('label[for="'+idCurrent+'"]').attr("style", "color: gray;"); 
    }); 
} 

在我的Entity/Foo.php中,我不得不使用setter和getter方法添加string類型的屬性「foo_disabled」。

相關問題