11

我有一个表格,其中包含数据库中实体的选择字段:

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

我想按值禁用此列表中的某些项目,但我不知道我应该在哪里拦截选择字段项目来做到这一点。

有人知道解决方案吗?

4

2 回答 2

12

只需使用事件侦听finishView器处理它。PRE_BIND

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
    ));

    $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;
        }
    }
}
于 2013-01-15T20:42:10.323 回答
12

您可以使用'choice_attr'in并传递一个函数,该函数将根据选择的值、键或索引来$form->add()决定是否添加 属性。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'] : [];
    },
...
于 2015-12-30T09:42:59.313 回答