2017-09-26 109 views
-1

只是想知道爲什麼這不起作用。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(),它將正常工作。

任何想法爲什麼返回不能作爲一個單獨的方法?或者我錯過了什麼。

感謝

回答

3

returnJson函數返回JsonResponseshowAccount功能,不出來。

這應該工作:

return $this->returnJson(); 
+0

感謝@svgrafov,原來如此! – BernardA