felixo
felixo

Reputation: 1613

How to add placeholder on input in Symfony 4 form?

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 ']])

Upvotes: 11

Views: 25911

Answers (4)

Marco Valeri
Marco Valeri

Reputation: 491

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

Upvotes: 1

You need to do like this :

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

As they say in the documentation

Upvotes: 32

This is worked in Symfony 4

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

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

Upvotes: 0

felixo
felixo

Reputation: 1613

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'}}) }}

Upvotes: 2

Related Questions