Disabling some checkboxes of choice widget in buildForm()

折月煮酒 提交于 2019-12-06 04:45:10

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!