How can I put the asterisk of my required field on my label? (Symfony form)

Mickaël Leger picture Mickaël Leger · Aug 18, 2017 · Viewed 8.1k times · Source

I am working on Symfony 3 and I have some trouble with my form.

When I create a Symfony form with a field not required, here is my code :

I create the form :

$form = $this->createFormBuilder()
  ->add('prenom' TextType::class, array(
    'label'    => 'Votre prénom',
    'required' => false
  )
  ->getForm();

Here is the code in my view for this field:

{{ form_label(form.prenom) }}
{{ form_errors(form.prenom) }}
{{ form_widget(form.prenom) }}

And this is the HTML I have :

<label class="control-label" for="contact_prenom">Votre prénom</label>
<input type="text" id="contact_prenom" name="contact[prenom]" class="form-control"/>

Now if I do the same without the 'require' => false on my FormBuilder, here is the HTML I get:

<label class="control-label required" for="contact_prenom">Votre prénom</label>
<sup class="required" title="Champ obligatoire">
        <i class="fa fa-asterisk"></i>
</sup>
<input type="text" id="contact_prenom" name="contact[prenom]" required="required" class="form-control" />

Is it possible to control the "sup" tag so the asterisk * can be with my label?

I guess I can do it with jQuery, but I'd like to know if it is possible to do it on my form builder or in Twig?

Answer

ste picture ste · Aug 18, 2017

In the doc there is a specific section here http://symfony.com/doc/current/form/form_customization.html#adding-a-required-asterisk-to-field-labels

You can even do with CSS only

label.required:before {
    content: "* ";
}