首页 > 解决方案 > 在 Symfony 5 表单构建器中修改 label_attr 字段

问题描述

在 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 字段可以这样做吗?

标签: formssymfonyformbuildersymfony5

解决方案


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 表单布局,但这不是必需的。


推荐阅读