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?
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: "* ";
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With