我有一个表单与数据库中的实体的选择字段:
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
解决方法
只需用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; } } }