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

问题描述 投票:0回答:2

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

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

我想按此列表中的值禁用某些项目,但我不知道应该在哪里拦截选择字段项目来执行此操作。

有人知道解决办法吗?

php symfony symfony-forms
2个回答
15
投票

您可以在

'choice_attr'
中使用
$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'] : [];
    },
...

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;
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.