Shlipack
Shlipack

Reputation: 11

Why do I get an error when adding an attribute to a form?

While learning Symfony I got this message after I have done a modification in the AppController.

Argument 2 passed to Symfony\Component\Form\FormBuilder::add() must be of the type string or null, array given, called in C:\wamp64\www\eHiring\src\Controller\AppController.php on line 49

My App controller code is the following:

public function formulaire()
    {
        $application = new Applications();

        $form = $this->createFormBuilder($application)
                    ->add("poste", [
                        'attr' => [
                            'class' => 'form-control'
                        ]
                    ])
                    ->add("pdf")
                    ->getForm();

        return $this->render('app/form.html.twig', [
            
            'form' => $form->createView(),
        
            
        ]);
    }

all was fine until I added the parameter for the class attribute for my form, this is what caused the issue.

I cannot find what is wrong.

My Twig code is :

{{ form_start(form) }}
    <div class="form-group">
        <label for="">Poste</label>
        {{ form_widget(form.poste)}}
    </div>
    <div class="form-group">
        <label for="">PDF</label>
        {{ form_widget(form.pdf)}}
    </div>
{{ form_end(form) }}

Upvotes: 0

Views: 159

Answers (1)

Micka Bup
Micka Bup

Reputation: 439

You should avoid creating all the options of your form in your controller. Create a new file as says the docs : https://symfony.com/doc/current/forms.html

When you create your formBuilder, you must explain what ur gonna add. For example, lets pretend 'poste' is a string. In your form it will be :

$builder
       ->add('poste', TextType::class, [
            'attr' => ['class' => 'form-control']

If you use Bootstrap, you don't need 'form-control'. Just say to Twig you use Bootstrap and he will do it for you.

The docs I gave you is really well written, you will be able to create good working and readable forms.

Upvotes: 1

Related Questions