I have a form widget of type "choice" which is being displayed as a list of many checkboxes. Everything works great. So to stress it out: there is ONE widget, with MANY checkboxes (and NOT several checkbox widgets).
Now, I want to disable some of those checkboxes. The data for that is avaliable in the $options-Array.
Here is the buildForm()-function of my 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')))
;
}
...
My Twig-template looks like this:
{% for foo in fooForm %}
<dd>{{ form_widget(foo) }}</dd>
{% endfor %}
I can only disable ALL the checkboxes (by setting 'disabled' => true in buildForm). And passing an array there does not work (as commented in the snippet).
How can I disable some selected checkboxed (stored in $options['choiceArray']['disabled']) of my choice widget?
I have solved the problem using JQuery.
- in my FooType.php I stringify the Array of fields that should be disabled.
- I pass that string in the buildForm()-Function via a hidden field to the template
- there I use JQuery to split the string again into IDs and process disable the checkboxes and grey out the label
Here is the PHP-Code (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))
;
}
...
Here is the JavaScript part (Twig-template):
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;");
});
}
In my Entity/Foo.php I had to add the property "foo_disabled" of type string with setter and getter methods.
来源:https://stackoverflow.com/questions/18299634/disabling-some-checkboxes-of-choice-widget-in-buildform