You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Symfony 4.4中EntityType的choice_attr属性不生效问题

问题解决:为Symfony复选框表单的归档项添加text-muted样式

当你使用EntityType并设置expanded: true(渲染为复选框)时,choice_attr会把类添加到复选框的<input>标签上,而不是显示文本的<label>标签,所以text-muted样式不会作用到文本上,这就是类未生效的原因。

下面提供两种可行的解决方案:

方案一:自定义表单主题(推荐,适合全局复用)

创建一个自定义表单布局模板,修改复选框的渲染逻辑,将choice_attr中的类传递给对应的<label>标签:

  1. 在templates/form/目录下创建custom_checkbox_layout.html.twig文件,内容如下:
{% block checkbox_radio_widget %}
    {% set label_attr = label_attr|merge({
        'class': (choice_attr.class is defined ? choice_attr.class ~ ' ' : '') ~ (label_attr.class is defined ? label_attr.class : '')
    }) %}
    {{ parent() }}
{% endblock %}
  1. 在使用表单的模板中引入这个自定义主题:
{% form_theme form 'form/custom_checkbox_layout.html.twig' %}

<div class="form-group">
   {{ form_label(form.prestationTypes, 'Types de tickets rattachés') }}
   {{ form_widget(form.prestationTypes) }}
</div>

这样原有的choice_attr逻辑就能正常将text-muted类应用到<label>上,文本会变浅显示。

方案二:手动渲染每个选项(适合单个表单快速实现)

直接在Twig模板中循环渲染每个复选框选项,手动为归档项的<label>添加类:

<div class="form-group">
    {{ form_label(form.prestationTypes, 'Types de tickets rattachés') }}
    {% for prestationType in form.prestationTypes %}
        <div class="form-check">
            {{ form_widget(prestationType) }}
            {{ form_label(prestationType, null, {
                'class': prestationType.vars.value.isArchived() ? 'text-muted form-check-label' : 'form-check-label'
            }) }}
        </div>
    {% endfor %}
</div>

这里直接通过prestationType.vars.value获取实体对象,调用isArchived()判断是否归档,然后为<label>添加对应的类。

内容的提问来源于stack exchange,提问作者Majo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 06:05:18