EntityType 不提供修改选项标签属性的选项。
你应该自己做。
1。简单的解决方案
迭代模板引擎中的选择,一个一个地渲染它。从选择中获取实体并设置标签属性。
{{ form_start(form) }}
{%- for choice in form.choices %}
<div>
{% set entity = form.choices.vars.choices[choice.vars.value].data %}
{{ form_widget(choice) }}
{{ form_label(choice, null, {
label_attr: {class: 'test-' ~ entity.number}
}) }}
</div>
{% endfor -%}
{{ form_end(form) }}
2。清洁溶液
创建自定义类型扩展EntityType:
https://symfony.com/doc/current/form/create_custom_field_type.html
在类型定义中创建允许闭包的新选项,例如"choice_label_attr" 并将闭包传递给视图:
// src/Form/Type/CustomEntityType.php
namespace App\Form\Type;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
class CustomEntityType extends AbstractType
{
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setRequired('choice_label_attr');
}
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['choice_label_attr'] = $options['choice_label_attr']
}
public function getParent(): string
{
return EntityType::class;
}
}
为选择类型扩展模板:
https://symfony.com/doc/current/form/form_themes.html#applying-themes-to-all-forms
在扩展模板中使用“choice_label_attr”回调:
{% use "bootstrap_4_layout.html.twig" %}
{% block custom_entity_widget_expanded -%}
<div {{ block('widget_container_attributes') }}>
{%- for child in form %}
{{- form_widget(child) -}}
{{- form_label(child, null, {class: choice_label_attr(form.choices.vars.choices[child.vars.value].data), translation_domain: choice_translation_domain}) -}}
{% endfor -%}
</div>
{%- endblock custom_entity_widget_expanded %}
更多信息:https://github.com/symfony/symfony/blob/5.x/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_4_layout.html.twig
使用示例:
use App\Form\Type\CustomEntityType ;
$builder->add('type', CustomEntityType::class, [
'class' => Resourcetype::class,
'multiple' => true,
'expanded' => true,
'choice_attr' => function (?Resourcetype $type) {
return [
'class' => sprintf('%s-parent parent', $type->getSafeName()) : $type->getSafeName()
];
});
解决方案 2. 是从头开始编写的,可能包含一些错误,但我希望您能理解。
两种解决方案都使用 Twig 和 Bootstrap 4 表单布局,但这不是必需的。