user23751544
user23751544

Reputation: 1

Symfony : send JsonResponse

I'm new to symfony as web programming and I'm having a hard time with the use of JSON response.

As you can see, the controller displays the entity content and create a form to add data in it. The form work fine and the array send by AJAX is added to the entity BUT the idea is to send back this data as a JSON response to update the entity content without refreshing the whole page.

Problem is that when the form is send, the JSON response replace the page and show something like :

{
"success": true,
"new_object": {
"id": 27,
"name": "thename",
"description": "thedescription",
"date": "2024-03-23T10:22:00+00:00",
}
}

I've thought that I should replace Response by JsonResponse when the function is defined but the render of the view send an error asking for a JSON response.

I also fought to create a new function to send the JSON response but because $form is handling the request i can't see how to add the form to the page is separate in another function.

How should i send this JSON response then ? Any help is really welcome 👍

<?php

namespace App\Controller;

use App\Entity\MyEntity;
use App\Form\OffresFormType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;

class MyEntityController extends AbstractController
{
    /**
     * @Route("/admin", name="administration", methods={"GET", "POST"})
     */
    public function admin(Request $request, EntityManagerInterface $entityManager): Response
    {

        $newobject = new MyEntity();
        $form = $this->createForm(MyEntityFormType::class, $newobject);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager->persist($newobject);
            $entityManager->flush();

            return $this->json(['success' => true, 'newobject' => $newobject]);
        }

        return $this->render('admin/entity.html.twig', [
            'entity_content' => $entityManager->getRepository(MyEntity::class)->findAll(),
            'form' => $form->createView(),
        ]);
    }
}

Upvotes: -1

Views: 73

Answers (1)

StAnto
StAnto

Reputation: 21

Try to use the JsonResponse to replace your return $this->json(), like this:

if ($form->isSubmitted() && $form->isValid()) {
   $entityManager->persist($newobject);
   $entityManager->flush();

   return new JsonResponse([
       'success' => true, 
       'newobject' => $newobject
   ]);
}

Upvotes: 0

Related Questions