Bradmage
Bradmage

Reputation: 1231

Add to Symfony form action

I've created a page with tabs (using bootstrap), and all tabs have their own form. And they all work well. My problem is when I get a form error, I want to open the tab that the error is on.

My current controller code:

public function add(Request $request, EntityManagerInterface $em): Response {

    $this->denyAccessUnlessGranted('ROLE_USER');

    $entityAdd = new \App\Entity\add();
    $form = $this->createForm(\App\Form\Add::class, $entityAdd);

    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {

Function in AddFormType.php

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
                ->add(...)
                ->add(...)
                ->add(...)
                ->getForm()
        ;
    }

I'm not creating the form myself, I'm using symfony form components but I'm not sure how to modify the form method to add the form hash (eg. /add#list-tab1) to the form method.

{{ form_start(AddForm) }}

{{ form_row(AddForm.name1) }}
{{ form_row(AddForm.name2) }}
{{ form_row(AddForm.save) }}

{{ form_end(AddForm) }}

Upvotes: 0

Views: 971

Answers (2)

yolenoyer
yolenoyer

Reputation: 9465

You can pass the action directly in the parameters of form_start(), in the Twig template:

{{ form_start(form, { action: '/add#list-tab1' }) }}

See the Symfony doc about this field option.

Upvotes: 2

Jonas Pariente
Jonas Pariente

Reputation: 141

You can pass the hash with the third parameter of createForm method :

$form = $this->createForm(
    \App\Form\Add::class,
    $entityAdd,
    ['action' => '#list-tab1']
);

Then, you can use the setAction() method and retrieve the option in the buildForm() method in your AddFormType.php file:

$builder
    ->setAction($options['action'])
    ->add(...)

Note: Using only the hash in the setAction() method (and not the full route), is only working if the form is submitted to the current route.

You'll have to replace #list-tab1 with the real tab id.

Upvotes: 5

Related Questions