Search code examples
formssymfonyoopformbuilder

How can I add an element into form created with formbuilder (Symfony)?


I create a form via formbuilder in Symfony4:

$formBuilder->add($fieldMapping['fieldName'], TextType::class, array('attr' => array('class' => 'form-control')));

This is giving me the following output:

<div>
   <label for="form_username" class="required">Username</label>
   <input type="text" id="form_username" name="form[username]"  class="form-control">
</div>

I would like to add a line after the input field, so the result looks like this:

<div>
   <label for="form_username" class="required">Username</label>
   <input type="text" id="form_username" name="form[username]" required="required" class="form-control">
   <span class="info" data-name="form[username]">
</div>

My approach:

$formBuilder->add($fieldMapping['fieldName'], TextType::class, array('attr' => array('class' => 'form-control', 'after' => "<span class='info' data-name='form[username]'></span>")));

But this is not correct


Solution

  • As @Ahmed EBEN HASSINE said, prefers twig form theming https://symfony.com/doc/current/form/form_customization.html#adding-help-messages

    Inside one template

    {% use 'form_div_layout.html.twig' with form_widget_simple as base_form_widget_simple %}
    
    {% block form_widget_simple %}
        {{ block('base_form_widget_simple') }}
        <span class="info" data-name="{{ full_name }}">
    {% endblock %}
    
    
    {# rest of your code #}
    

    For all your templates, create a base file

    {# template/form/fields.html.twig #}
    {% extends 'form_div_layout.html.twig' %}
    
    {% block form_widget_simple %}
        {{ parent() }}
    
        <span class="info" data-name="{{ full_name }}">
    {% endblock %}
    

    and declare it in your configuration

    # config/packages/twig.yaml
    twig:
        form_themes:
            - 'form/fields.html.twig'