11

In my Symfony 4 form, I am try to get a placeholder for my input. I tried the below but I get an error that it is not allowed. Any ideas how else I can achieve this?

        ->add('firstname', TextType::class, ['label' => 'Vorname ', 'placeholder' => 'Your name',])

As suggested in the documentation I have also tried the below, here I am not getting an error, just nothing is rendering.

        ->add('firstname', TextType::class, ['label' => 'Vorname '], ['attr' => ['placeholder' => 'Vorname ']])
felixo
  • 1,453
  • 6
  • 33
  • 60

4 Answers4

30

You need to do like this :

->add('firstname', TextType::class, array(
      'label' => 'Vorname ',
      'attr' => array(
          'placeholder' => 'hereYourPlaceHolder'
      )
 ))

As they say in the documentation

crmpicco
  • 16,605
  • 26
  • 134
  • 210
  • Albeit different syntax, I have tried what they have suggested but still nothing! This is what I tried: ->add('firstname', TextType::class, ['label' => 'Vorname '], ['attr' => ['placeholder' => 'Vorname ']]) – felixo Apr 16 '19 at 15:46
  • There is no 'placeholder' option in TextType... Take a look about my answer. – Nicolas Apr 17 '19 at 06:46
  • 1
    Or you can use like this directly in the Twig : {{ form_widget (form.firstname.first, {'attr': {'placeholder': 'Vorname '}}) }} – Nelson Rodrigues Marreiros Apr 17 '19 at 07:19
  • Strangely, this doesn't work for me in Symfony 4.4. I have had to resort to @kontenurban 's answer below and pass through the placeholder in the Twig template. For the life of me I can't see why I have to do this because the answer here makes sense to me and aligns with the documentation. Strange one. – crmpicco Apr 08 '21 at 02:22
2

This also works, by rendering the items individually and adding an attribute in the twig!

{{ form_label(form.firstname) }}
{{ form_widget(form.firstname, {'attr': {'placeholder': 'FIRSTNAME'}}) }}
felixo
  • 1,453
  • 6
  • 33
  • 60
1

The documentation of Symfony 6 suggests two ways.

The first option is inside the yourForm.php:

->add('name', TextType::class,
    [
        'label'    => 'Name *',
        'attr' => ['placeholder' => 'Name *'],
        'required' => true
    ])

The second option is inside the twig template:

{{ form_label(form.name) }}
{{ form_widget(form.name, {'attr': {'placeholder': 'Name*' }}) }}

You can find more information in the official documentation of Symfony 6 FormType

Marco Valeri
  • 401
  • 3
  • 5
0

This is worked in Symfony 4

            ->add('fullName', null, [
                'label' => 'Kontaktperson',
                'attr' => [
                    'placeholder' => 'Contact person name'
                ],
            ]) 

More details: http://toihid.com/?p=326