Symfony2:创建两个控制器,一个用于显示表单,另一个用于处理提交


Symfony2: Create two controllers one to display a form and other to handle the submission

嗨,我是Symfony2 MVC框架的新手。到目前为止,我所实现的是使用twig模板在twig模板中呈现表单。接下来我要做的是创建第二个(单独的)控制器来处理表单提交。你能告诉我如何做到这一点吗?

我已经阅读了symfony2文档,但是,它不工作。

非常感谢

您需要在生成的表单上设置一个操作,如下所示:

public function generateSearchBarAction()
{
    $form = $this->createFormBuilder()
        //This is where we are defining the target route
        ->setAction($this->generateUrl('route_to_catch_the_request'))
        ->setMethod('POST')
        ->add('keyword')
        ->getForm()
    ;
    return $this->render('search_bar.html.twig', array(
        'form' => $form->createView()
    ));
}

route_to_catch_the_request处提供的控制器可以捕获请求。

public function showSearchKeywordsAction(Request $request)
{
    $form->handleRequest($request);
    if ($form->isValid()) {
         //do whatever...
    }
}