Symfony 4 - 在表单提交后将响应传递给另一个视图

Symfony 4 - passing response to another view after form submit

我的 symfony 项目中有两种方法。我正在构建一个表单,在提交时需要使用它的响应在新视图中重定向。

我一直收到错误消息,但奇怪的是,我的响应是 运行 就像第一种方法应该的那样,但第二种方法我一直收到错误消息:

Could not resolve argument $date of "App\Controller\ItController::render()", maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"?

public function getIt(Request $request)
{
    $form = $this->createFormBuilder()
        ->add('startDate', DateTimeType::class, [
            'data' => new \DateTime('first day of this month'),
            'widget' => 'single_text',
            'html5' => false,
        ])
        ->add(
            'save',
            SubmitType::class,
            [
                'label' => 'Generate Billing Report',
                'attr' => ['class' => 'btn-submit btn-primary action-save']
            ]
        )
        ->getForm();

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $data = $form->getData();
        $startDate = $data['date'];

        $this->render($date->format('Y-m-d'));


        return $this->redirectToRoute('rr');
    }

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

以及需要生成带有响应的第二个视图的其他方法:

/**
 * @Route("/test", name="rr")
 */
public function render($date)
{
    $response = $this->someService('route/defined/from/other/external/service, $date);
    dump($response);

    return $this->render('response.html.twig', [
        'response' => $response
    ]);
}

当我在第一种方法中转储响应时,它 return 成功了,但是当我尝试将它传递给另一种方法时,它 return 出现了这个错误。也许有一个选项可以在第一种方法中呈现第二个视图? 有人可以帮忙吗?谢谢

这里的问题是您正在重新定义 AbstractController::render 方法并且它使用错误的参数类型调用自身。

public function render($date)
{
    $response = $this->someService('route/defined/from/other/external/service', $date);
    dump($response);

    // next line calls this method that we are in App\Controller\ItController::render($date) and throws the error
    return $this->render('response.html.twig', [
        'response' => $response
    ]);
}

将其更改为

public function renderExternalResponse($date)
{
    $response = $this->someService('route/defined/from/other/external/service', $date);

    return $this->render('response.html.twig', [
        'response' => $response
    ]);
}

然后像这样更改您处理提交表单的方式:

if ($form->isSubmitted() && $form->isValid()) {
    $data = $form->getData();
    $startDate = $data['date'];

    return $this->renderExternalResponse($date->format('Y-m-d'));
}