简体   繁体   中英

Symfony3 Form builder setAction won't redirect to route

I have a form controlling the search bar in the websites navbar:

public function searchFormAction()
    {
        $form = $this->createFormBuilder()
            ->setAction($this->generateUrl('search'))
            ->setMethod('GET')
            ->add("value", TextType::class, array('label' => false))
            ->add("Search", SubmitType::class)
            ->getForm();

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

As you can see, the form has a specific action path to this function:

/**
     * @Route("/search", name="search")
     */
    public function searchAction(Request $request)
    {
        return $this -> render ("post/post-search.html.twig", [
            "value" =>  $request->query->get('value')
        ]);
    }

For now this shouldn't do much more than just display the value on the page.

The problem is that the website fails to redirect when the form is used

So when I put foo in the search, and click submit the path looks like this:

localhost:8000/page?form%5Bvalue%5D=foo&form%5BSearch%5D=&form%5B_token%5D=PsouIRAy2QaQ8j2XO_uYrs7PcaR6jyjQN3W3_xRMdgw

Moreover if I go to localhost:8000/search and try to put anything into the search bar, no value is printed.

Here is how the form is rendered:

//search-form.html.twig
<form class="navbar-form navbar-left">
    {{ form_start(form) }}
    <div class="form-group">
        {{ form_row(form.value) }}
    </div>
    {{ form_row(form.Search) }}
    {{ form_end(form) }}
</form>

And placed in the base navbar:

//base.html.twig
//...
 {{ render(controller(
                'AppBundle:Form:searchForm'
                )) }}
//...

Inspecting the element shows that the form tag has no action and method attributes

What could be the issue here and how can I fix it?

Fixed! Made a simple mistake in the twig file. Placed the form start inside html form tags, that way the submit button would send to an empty form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM