0

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

1
  • 1
    Whether you override the form rending using form theming you can ispire from this example symfony.com/doc/current/form/… Commented Nov 21, 2018 at 18:07

2 Answers 2

1

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'
Sign up to request clarification or add additional context in comments.

Comments

1

You can print individual label & widget in Twig.

<div>
    {{ form_label(form.fieldName) }}
    {{ form_widget(form.fieldName) }}
    <span class="info" data-name="form[username]">
</div>

1 Comment

Not sure why the downvotes. This is an acceptable approach. Instead of string form[username] I would add form.username.vars.full_name though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.