修改Symfony 5表单生成器中的label_attr字段



在symfony表单生成器中构建表单时,可以更改choice属性。但是,对于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

在类型定义中创建允许闭包的新选项,例如";选择标签属性"并通过关闭查看:

// src/Form/Type/CustomEntityType.php
namespace AppFormType;
use SymfonyComponentOptionsResolverOptionsResolver;
use SymfonyBridgeDoctrineFormTypeEntityType;
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-所有形式的主题

使用";选择标签属性"扩展模板内部的回调:

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

最新更新