如何禁用表单选择类型中的特定项目? [英] How to disable specific item in form choice type?

查看:19
本文介绍了如何禁用表单选择类型中的特定项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a form with choice field of entities from database:

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

此表单将生成复选框列表并将呈现为:

This form will produce the list of checkboxes and will be rendered as:

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

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

I want to disable some of the items by value in this list but I don't know where I should intercept choice field items to do that.

有人知道解决方案吗?

推荐答案

刚刚用 finishViewPRE_BIND 事件监听器处理了.

Just handled it with finishView and PRE_BIND event listener.

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

这篇关于如何禁用表单选择类型中的特定项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆