E
E
Eugene Wolf2016-11-10 00:34:08
symfony
Eugene Wolf, 2016-11-10 00:34:08

How to add a default class to a form element when it is themed by Symfony3?

Good day dear!
Learning to themize forms in Symfony3 / Twig. I want to change the standard block form_widget_simpe:

{% block form_widget_simple %}
    {% set type = type|default('text') %}
    <input type="{{ type }}" {{ block('widget_attributes' }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
{% endblock form_widget_simple %}

Here, name , id , required and other fields widget_attributesare displayed in the block . Can you please tell me how to set the default "class" parameter for this block? That is, what would be displayed, among other fields, by default
<input ... class="my-class" ... />

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
ig0r88, 2016-11-10
@Wolfnsex

{%- block form_widget_simple -%}
    {%- set type = type|default('text') -%}
    {%- if attr.class is not defined -%}
        {%- set attr = attr|merge({'class': 'my-class'}) -%}
    {%- endif -%}
    <input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
{%- endblock form_widget_simple -%}

Or if you want to always add a class:
{%- block form_widget_simple -%}
    {%- set type = type|default('text') -%}
    {%- set attr = attr|merge({'class': (attr.class|default ~ ' my-class')|trim}) -%}
    <input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
{%- endblock form_widget_simple -%}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question