forms - 在 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 字段可以这样做吗?
解决方案
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 %}
使用示例:
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 表单布局,但这不是必需的。
推荐阅读
- python - Python HTML抓取找不到我知道存在的属性?
- git - 如何使用组织 git hub 登录 Gitkraken
- r - 如何在列中查找所有组合并计算数据中的出现次数
- linux - 如何使用 grep 匹配作为变量(而不是整行)
- arrays - Numpy 切片并加入
- json - 如何从 JSON 文件中创建 UML 模式?
- python - TypeError:传递给参数“indices”的值的 DataType float32 不在允许值列表中:int32、int64
- java - 访问 JTextField 文本
- angular - Angular 8:运行 ng serve 时“找不到构建器的实现”
- esp8266 - 将代码上传到 ESP8266 时出现问题:esptool.FatalError:无法连接到 ESP8266:等待包头超时