Symfony2 how to remove label for the field using FormBuilder
Solution 1
You can extend the default form layout using your own twig-file for your fields like this:
<!-- import default layout from symfony -->
{% use 'form_div_layout.html.twig' with field_label as base_field_label %}
<!-- overwrite the element you want to change (in this case default input-field -->
{% block field_row %}
{% spaceless %}
<div class="row">
<!-- removing this line, you're nearly done -->
{{ form_label(form) }}
{{ form_widget(form) }}
</div>
{% endspaceless %}
{% endblock field_row %}
And afterwards you set this new form theme in the twig file which renders the form:
{% form_theme form 'VendorNameBundle:Folder:backend_fields.html.twig' %}
That's pretty much it.
If you want to know, what are all the default values, take a look at this file in the repository: form_div_layout.html.twig
Solution 2
I just tested this working solution with sf2.4.6 :
$builder->add('body','text',array('label' => false);
This solution is better than
label => ' '
which is just rendering a single space. Moreover you don't need to split your rendering in form_widget and form_label to finally removing form_label.
Solution 3
better solution is just:
[..Type.php]
$builder
->add('email', EmailType::class ) //will display default label
->add('username', TextType::class,
array(
'label' => false,
'attr' => array(
// 'class' => 'myclassfrom.css', //<- this one is realy avesome
'placeholder' => 'UsernameExample',
'autofocus' => '',
),
))
and all You need is just to put in your related twig
{{ form_start(form) }}
{{ form_row(form.username) }}
{{ form_end(form) }}
Related videos on Youtube
Mikhail
CTO at Umbrella-web company Umbrella Web Studio offers you the creation of sharp, up-to-date Web applications with extensible functionality and scalability for high traffic loads. The company offers a wide range of experience in the creation of successful commercial projects.
Updated on September 14, 2022Comments
-
Mikhail over 1 year
$builder->add('body','text',array('label' => FALSE)//default label is displayed $builder->add('body','text',array('label' => '')//default label is displayed $builder->add('body','text',array('label' => 0)//default label is displayed $builder->add('body','text',array('label' => ' ')//empty label is displayed
But I don't need to render a
label
tag. I use aform_widget(form)
inthe view and I can't use aform_row(form.field1) ... form_row(form.field25)
to display a forms. I want to remove label only using a FormBuilder. It's possible? -
Mikhail over 11 yearsOK, I understood, it's inpossible with FormBuilder only. Thanks
-
madc over 11 yearsSetting labels to false in the formbuilder has been implemented with this commit: Option for not displaying a label by setting label to false.