如何在我的标签上添加必填字段的星号?(Symfony表单)

5

我是一名Symfony 3开发者,我的表单出了一些问题。

当我创建一个不需要填写的Symfony表单时,这是我的代码:

我创建了表单:

$form = $this->createFormBuilder()
  ->add('prenom' TextType::class, array(
    'label'    => 'Votre prénom',
    'required' => false
  )
  ->getForm();

这是我视图中针对该字段的代码:

{{ form_label(form.prenom) }}
{{ form_errors(form.prenom) }}
{{ form_widget(form.prenom) }}

以下是我现有的HTML代码:

<label class="control-label" for="contact_prenom">Votre prénom</label>
<input type="text" id="contact_prenom" name="contact[prenom]" class="form-control"/>

现在,如果我在我的 FormBuilder 上不加上 'require' => false,那么我得到的HTML如下:
<label class="control-label required" for="contact_prenom">Votre prénom</label>
<sup class="required" title="Champ obligatoire">
        <i class="fa fa-asterisk"></i>
</sup>
<input type="text" id="contact_prenom" name="contact[prenom]" required="required" class="form-control" />

是否可以控制 "sup" 标签,使星号 * 跟我的标签一起显示?

我想可以通过 jQuery 实现,但我想知道是否可以在我的表单构建器或 Twig 中实现?

3个回答

24

这就是我最终做的,我在CSS中使用了“*”并在jQuery中删除了“sup”。虽然不是很干净的解决方案,但主要开发人员告诉我要使用CSS,我现在是实习生所以听从他的建议^^ - Mickaël Leger

2

0

是的,您可以覆盖Twig模板或Symfony用于呈现小部件的块,请参阅: http://symfony.com/doc/current/templating/overriding.html

在您的情况下,您正在寻找

vendor/symfony/symfony/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig

这将是您想要覆盖的代码块:

{%- block form_label -%}
    {% if label is not same as(false) -%}
        {% if not compound -%}
            {% set label_attr = label_attr|merge({'for': id}) %}
        {%- endif -%}
        {% if required -%}
            {% set label_attr = label_attr|merge({'class': (label_attr.class|default('') ~ ' required')|trim}) %}
        {%- endif -%}
        {% if label is empty -%}
            {%- if label_format is not empty -%}
                {% set label = label_format|replace({
                    '%name%': name,
                    '%id%': id,
                }) %}
            {%- else -%}
                {% set label = name|humanize %}
            {%- endif -%}
        {%- endif -%}
        <label{% if label_attr %}{% with { attr: label_attr } %}{{ block('attributes') }}{% endwith %}{% endif %}>{{ translation_domain is same as(false) ? label : label|trans({}, translation_domain) }}</label>
    {%- endif -%}
{%- endblock form_label -%}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接