symfony 3 - 控制器返回单独函数生成错误

问题描述:

只是想知道为什么这不起作用。symfony 3 - 控制器返回单独函数生成错误

放置在单独的方法中的JSON返回当我在控制器得到下面的错误:

The controller must return a response (null given). Did you forget to add a return statement somewhere in your controller? (500 Internal Server Error) 

的设置是这样的:

控制器

namespace UsedBundle\Controller; 

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 
use Symfony\Bundle\FrameworkBundle\Controller\Controller; 
use Symfony\Component\HttpFoundation\Request; 
... 
use Symfony\Component\HttpFoundation\JsonResponse; 


class AccountController extends Controller 
{ 
private $status; 
private $message; 
private $data; 

/** 
* @Route("/mon-compte", name="account_page") 
*/ 

public function showAccount(Request $request){ 
    $factory = $this->get('security.encoder_factory'); 
    if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_REMEMBERED')) { 
     throw $this->createAccessDeniedException(); 
    } 
    $user = $this->getUser(); 
    $session = $request->getSession(); 
    $email = $session->get('email'); 

    $em = $this->getDoctrine('doctrine')->getManager('used'); 
    $this->user_info = $em->getRepository('UsedBundle:User') 
    ->UserAccountInfoAction($email); 

    $form = $this->createForm(UserType::class, $user); 
    if ($request->isMethod('POST')) { 
     if($_POST['action'] == 'update_user'){ 
      $this->updateProfile($request, $user, $form, $em); 
     }elseif($_POST['action'] == 'delete_user'){ 
      $this->deleteUser($user, $em); 
     }elseif($_POST['action'] == 'update_password'){ 
      $this->updatePassword($user, $em, $factory); 
     } 
       // \Doctrine\Common\Util\Debug::dump($this->data); 
     $this->returnJson();//***** this is generating the error***** 
    }else{ 
     // populate change profile form 
     return $this->render('account/account.html.twig', [ 
      'user_info' => $this->user_info, 
      'form' => $form->createView(), 
     ]); 
    } 
} 

,然后,进一步在那个类上我有returnJson()方法:

public function returnJson(){ 
    return new JsonResponse(array(
     'status' => $this->status, 
     'message' => $this->message, 
     'data' => $this->data, 
     ) 
    );   
} 

如果我放置该代码替换$ this-> returnJson()showAccount(),它将正常工作。

任何想法为什么返回不能作为一个单独的方法?或者我错过了什么。

感谢

returnJson函数返回JsonResponseshowAccount功能,不出来。

这应该工作:

return $this->returnJson(); 
+0

感谢@svgrafov,原来如此! – BernardA