【问题标题】:The controller must return a response, action is never executed控制器必须返回响应,动作永远不会执行
【发布时间】:2013-08-05 18:37:51
【问题描述】:

我的控制器中有这段代码:

/**
 * Displays a form to create a new Bank Account
 *
 * @Route("/account/new", name="wba_new")
 * @Method("GET")
 * @Template("BankBundle:BankAccount:new.html.twig")
 */
public function newBankAccountAction() {
    $entity = new Account();
    $form = $this->createForm(new AccountType(), $entity);

    return array('entity' => $entity, 'form' => $form->createView());
}

/**
 * Handle bank account creation
 *
 * @Route("/", name="wba_create")
 * @Method("POST")
 */
public function createAction(Request $request) {
    $entity = new Account();
    $form = $this->createForm(new AccountType(), $entity);
    $form->handleRequest($request);

    print_r($request);
    exit;

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();

        return $this->redirect($this->generateUrl('wba_list'));
    }

    return array('entity' => $entity, 'form' => $form->createView());
}

当我调用/account/new 时,表单显示没有任何问题,操作转到/,但是当我发送表单时出现此错误:

控制器必须返回一个响应(Array(entity => 对象(BankBundle\Entity\AccountType),形式 => 对象(Symfony\Component\Form\FormView)))。

为什么?我的代码有什么问题?

更新

我发现问题出在哪里,我在两个不同的控制器中有两条定义相同的路由:

/**
 * Handle bank account creation
 *
 * @Route("/", name="wba_create")
 * @Method("POST")
 */

解决问题后一切正常

【问题讨论】:

  • 控制器动作不应该返回某种Response 对象吗?
  • @JoachimIsaksson 并非总是如此,请参阅我的版本
  • @JoachimIsaksson 是对的。您忘记了 createAction() 函数顶部的 @Template 注释。
  • 控制器应始终返回响应。模板注释使模板被渲染并构建响应(并最终返回)。
  • 请添加您的解决方案(具有相同定义的两条路线)作为答案并接受它,以便将问题标记为已解决。虽然这是您的解决方案...我猜 95% 面临此问题的人忘记了 SensioFramworkExtraBundle 的 @Template 注释或忘记激活 FOSRestBundle 的视图响应侦听器...或任何其他侦听器转换控制器操作返回的数据自动进入响应对象。

标签: symfony symfony-forms symfony-2.3


【解决方案1】:

再次完整阅读代码并尝试找出我的错误所在,终于找到了。我有两个控制器:AccountController.phpTestController.php,在这两个控制器中我都定义了(我的错误,因为我刚刚将 AccountController.php 复制到 TestController.php)与此函数中相同的路由:

/**
 * Handle bank account creation
 *
 * @Route("/", name="wba_create")
 * @Method("POST")
 */
public function createAction(Request $request) {
    ...
}

出于这个原因,我很坚强,这就是为什么当 Symfony 尝试调用路由 wba_create 时数据丢失的原因。我没有添加注释@Template("")。这就是解决方案,希望适用于任何运行相同问题的人

【讨论】:

    【解决方案2】:
    /**
     * Displays a form to create a new Bank Account
     *
     * @Route("/account/new", name="wba_new")
     */
    public function newBankAccountAction()
    {
        $entity = new Account();
        $form = $this->createForm(new AccountType(), $entity);
    
        return $this->render('BankBundle:BankAccount:new.html.twig',array(
                'entity' => $entity,
                'form' => $form->createView(),
        ));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-04
      • 1970-01-01
      • 1970-01-01
      • 2014-01-08
      相关资源
      最近更新 更多