Html in label choice form

Viewed 2627

In choiceType field I have parameter - choice label

   'choice_label' => function ($pay, $key, $index) {
        return "<b>".$pay->getName()."</b><br />";
    },

And render function of fields in twig:

{{form_widget(field)}}
{{form_errors(field)}}

Of course I want to render getName in bold characters, I have try with twig autoescape and {{form_widget(field)|raw}} - without success

1 Answers

You have to custom the choice_label form in a custom theme (ex : radioHTML.html.twig) => I just add |raw to the label text

{%- 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 -%}
    <{{ element|default('label') }}{% if label_attr %}{% with { attr: label_attr } %}{{ block('attributes') }}{% endwith %}{% endif %}>
    {%- if translation_domain is same as(false) -%}
        {{- label|raw -}}
    {%- else -%}
        {{- label|trans({}, translation_domain)|raw -}}
    {%- endif -%}
    </{{ element|default('label') }}>
{%- endif -%}
{%- endblock form_label -%}

Your form type just return html string in the choice_label option :

 $builder->add('fieldName', EntityType::class, array(
            'required' => true,
            'class' => 'AppBundle\EntityName',
            'choice_label' => function (EntityName $entity) {
                $html = '<div>';
                $html .= $entity->getName();
                $html .= '</div>';
                return $html;
            },
            'data' => null,
            'multiple' => false,
            'expanded' => true)

And then use it for your specific field like that in your twig TPL :

{% form_theme from.fieldNalme 'form/radioHTML.html.twig' %}
Related