简体   繁体   English

Symfony表单重定向到控制器而不是路由

[英]Symfony form redirect to controller instead of route

Using Symfony 3.4 使用Symfony 3.4

I have this form in which the user selects a color, and when you submit the form, instead of redirecting to a route, I forward the data submitted to a controller: 我有一个用户可以在其中选择颜色的表单,当您提交表单时,我将提交的数据转发给控制器,而不是重定向到路由:

public function selectColorAction(Request $request)
{



$form = $this->createForm(pickColorType::class);
$form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) 

    {
        $data = $form["color"]->getData();
        $getColorId = $data->getId();


        $response = $this->forward('AppBundle:Products:selectPaint', 
        array(
        'color'=>$getColorId,


        )); 
        return $response;
    }

}

This is the controller that receives the data submitted from the previous form: 这是接收从先前表单提交的数据的控制器:

public function selectPaintAction($color, Request $request)
{
    $form = $this->createForm(BrandNameType::class);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) 
    {
        //something
    }

    return $this->render('AppBundle:Color:enter-brand-name.html.twig',
    array(
     'form'=> $form->createView()
    )
    );
}

The problem is that my forwarding not only sends the data, but also the first form, causing an error. 问题是我的转发不仅发送数据,还发送第一种形式,从而导致错误。 The profiler shows both forms: PickColor and the BrandName form. 分析器显示两种形式:PickColor和BrandName表单。 I only want the BrandName after forwarding. 转发后我只想要BrandName。 What can I do? 我能做什么?

If you look a bit further into what the forward method does: 如果您进一步研究forward方法的作用:

protected function forward($controller, array $path = array(), array $query = array())
{
    $request = $this->container->get('request_stack')->getCurrentRequest();
    $path['_forwarded'] = $request->attributes;
    $path['_controller'] = $controller;
    $subRequest = $request->duplicate($query, null, $path);

    return $this->container->get('http_kernel')->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
}

it clones the current request with $request->duplicate . 它使用$request->duplicate克隆当前请求。 The duplicate copies the posted values (and other things). 重复项将复制已过帐的值(和其他内容)。

You could try to remove the submitted form data from the request manually before triggering the forward. 您可以尝试在触发转发之前从请求中手动删除提交的表单数据。

Which would look like this: 看起来像这样:

$request->request->remove('THE_NAME_OF_YOUR_FORM_PARAMETER'); 
#what your getBlockPrefix of the PickColorType returns

If symfony doesn't inject a clone of the original request into the controllers it should work. 如果symfony没有将原始请求的副本注入控制器,则它应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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