感谢@ user2268997对choice_attr的评论,我找到了相关的博客文章
New in Symfony 2.7: Choice form type refactorization,其中详细介绍了使用(截至目前未记录的)choice_attr选项.
在渲染字段时,似乎Symfony将choice_attr中的属性与attr中的属性合并.这意味着我们需要覆盖choice_attr中的class属性.
我尝试在我定义attr的旁边的代码中执行此操作但没有运气.您似乎需要在表单类型定义中执行此操作.这是添加choice_attr选项后从我的表单中摘录的:
namespace MyBundle\Form;
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('roles',
'entity',
[
'class' => 'MyBundle:Role',
'choice_label' => 'name',
'multiple' => true,
'choice_attr' => function () { return ["class" => ""]; }
]);
}
结果就像我所希望的那样.我可能还会将它重构为我自己的自定义表单类型,因此我不需要在我的包中重复它.
我现在决定创建一个具有上述所需行为的自定义选择类型,并在整个应用程序中使用该类型.
这是我的选择类型:
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ChoiceNoOptAttrType extends ChoiceType {
public function configureOptions(OptionsResolver $resolver) {
parent::configureOptions($resolver);
$resolver->setDefault("choice_attr", function () { return ["class" => ""]; });
}
}
我不想重构所有现有的表单来使用这种新类型,所以我选择用我的替换Symfony提供的选择类型.这可以通过修改选择表单类型的服务配置来实现.为此,我为我的bundle创建了一个编译器传递.
namespace MyBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class MyCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$definition = $container->getDefinition("form.type.choice");
$definition->setClass('MyBundle\Form\ChoiceNoOptAttrType');
}
}
现在剩下要做的就是在bundle中注册编译器传递.
namespace MyBundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use MyBundle\DependencyInjection\Compiler\MyCompilerPass;
class MyBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new MyCompilerPass());
}
}
就是这样.现在我所有选择的字段都使用我的自定义类,这确保attr中设置的CSS类不会传播到我的< option>元素.