问题描述
在 symfony 表单构建器中构建表单时,可以更改选择属性。 但是,对于 label 属性,这似乎是不可能的。
这是我如何修改选择:
$builder->add('type',EntityType::class,[
'class' => Resourcetype::class,'multiple' => true,'expanded' => true,'choice_attr' => function (?Resourcetype $type) {
return ['class' => $type->getSafeName() . '-parent parent' : $type->getSafeName()
];
});
这对 label_attr 字段是否可行?
解决方法
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,{class: choice_label_attr(form.choices.vars.choices[child.vars.value].data),translation_domain: choice_translation_domain}) -}}
{% endfor -%}
</div>
{%- endblock custom_entity_widget_expanded %}
用法示例:
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 表单布局,但这不是必需的。