Vla*_*viy 11 symfony-forms 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
));
}
Run Code Online (Sandbox Code Playgroud)
此表单将生成复选框列表,并将呈现为:
[ ] Category 1
[ ] Category 2
[ ] Category 3
Run Code Online (Sandbox Code Playgroud)
我想在此列表中按值禁用某些项目但我不知道在哪里拦截选择字段项目来执行此操作.
有人知道解决方案吗?
Vla*_*viy 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
Jac*_*mri 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'] : [];
},
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11114 次 |
| 最近记录: |