symfony – 如何禁用表单选择类型中的特定项目?

前端之家收集整理的这篇文章主要介绍了symfony – 如何禁用表单选择类型中的特定项目?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个表单与数据库中的实体的选择字段:
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
    ));
}

此表单将生成复选框列表,并将显示为:@H_404_5@

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

我想通过此列表中的值禁用某些项目,但我不知道应该截取选择字段项目.@H_404_5@

有人知道解决方案吗?@H_404_5@

解决方法

只需用finishView和PRE_BIND事件侦听器处理它.
public function buildForm(FormBuilderInterface $builder,'empty_value' => false
    ));

    $builder->addEventListener(FormEvents::PRE_BIND,function (FormEvent $event) {
        if (!$ids = $this->getNonEmptyCategoryIds()) {
            return;
        }

        $data = $event->getData();

        if (!isset($data['categories'])) {
            $data['categories'] = $ids;
        } else {
            $data['categories'] = array_unique(array_merge($data['categories'],$ids));
        }

        $event->setData($data);
    });
}

...

public function finishView(FormView $view,FormInterface $form,array $options)
{
    if (!$ids = $this->getNonEmptyCategoryIds()) {
        return;
    }

    foreach ($view->children['categories']->children as $category) {
        if (in_array($category->vars['value'],$ids,true)) {
            $category->vars['attr']['disabled'] = 'disabled';
            $category->vars['checked'] = true;
        }
    }
}
原文链接:/html/224017.html

猜你在找的HTML相关文章