Raphael_b Raphael_b - 2 months ago 80
Twig Question

Symfony-Twig: insert fontawesome icon in a form_widget

To validate a form I am using a standard:

{{ form_widget(form.save, {'attr': {'class': 'btn btn-sm btn-danger'}, 'label': 'Submit form'}) }}


I want to insert a fontawsome icon in the button. I tried:

{{ form_widget(form.save, {'attr': {'class': 'btn btn-sm btn-danger'}, 'label': '<i class="fa fa-envelope-o"></i> Submit form'}) }}


But it is not working; obviously

Any idea how to that?

Answer

I would define a new form template in the same view (or in a template if you need to reuse the code). More details here

{% extends '::base.html.twig' %}

{% form_theme form _self %}

{%- block submit_widget -%}
    {%- set type = type|default('submit') -%}

    {%- 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 -%}
    <button type="{{ type|default('button') }}" {{ block('button_attributes') }}>
        <i class="fa fa-envelope-o"></i>
        {{ label|trans({}, translation_domain) }}
    </button>
{%- endblock submit_widget -%}


{% block content %}
    {# ... render the form #}

    {{ form_row(form.age) }}
{% endblock %}

EDIT

Also, it could be interesting to customize (accept HTML raw in the label) only the label submit button by ID. More details chapter How to Customize an individual Field of the link above.

Replace product_name by your submit ID and your syntax {{ form_widget(form.save, {'attr': {'class': 'btn btn-sm btn-danger'}, 'label': '<i class="fa fa-envelope-o"></i> Submit form'}) }}

{% block _product_name_label %}
     <label>{{ label|raw }}</label>
{% endblock %}
Comments