BernardA BernardA - 27 days ago 5
JSON Question

symfony 3 - controller return on separate function generates error

Just wondering why this does not work.

I am getting the error below in a controller when placing the JSON return in a separate method:

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

The setup is like this:


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*****
// populate change profile form
return $this->render('account/account.html.twig', [
'user_info' => $this->user_info,
'form' => $form->createView(),

and then, further down on that class I have the returnJson() method:

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

If I place that code replacing the $this->returnJson() on showAccount(), it will work correctly.

Any ideas why the return can't be placed as a separate method? Or am I missing something.


Answer Source

Your returnJson function returns JsonResponse into showAccount function, not out of it.

This should work:

return $this->returnJson();