Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 887
Mickaël Leger Avatar asked Nov 29 '22 08:11

Mickaël Leger


2 Answers

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: "* ";
}
like image 105
ste Avatar answered Dec 19 '22 15:12

ste


As of Symfony 5.1 you can do the following

->add('name', TextType::class, [
    'label' => 'Name <span class="badge badge-danger badge-pill">Required</span>',
    'label_html' => true
])

The label_html (bool) property will allow HTML to be injected into the label directly and render on the form output.

Documentation - https://symfony.com/doc/current/reference/forms/types/form.html#label-html

like image 31
hppycoder Avatar answered Dec 19 '22 14:12

hppycoder