Paul A.
Paul A.

Reputation: 597

Symfony2 CRUD, GET returns JSON but POST creates EMPTY records and PUT does nothing

I am new to Symfony2 and many bundles but I am working on a prototype REST API and I have used the FOSRestBundle and also playing around with the native CRUD generated by Symfony2. However, I have found that while the Symfony2 CRUD code returns the correct JSON formatted response, POST gives me an error and I am looking for explanations and tutorials on how to solve the problem. Look at the code for both GET and POST for an entity, lets say address in this case:

/**
 * Lists all Address entities.
 *
 * @Route("/", name="address")
 * @Method("GET")
 * @Template()
 */
public function indexAction()
{
    $em = $this->getDoctrine()->getManager();

    $entities = $em->getRepository('MyWebServicesBundle:Address')->findAll();

    return array(
        'entities' => $entities,
    );
}
/**
 * Creates a new Address entity.
 *
 * @Route("/", name="address_create")
 * @Method("POST")
 * @Template("MyWebServicesBundle:Address:new.html.twig")
 */
public function createAction(Request $request)
{
    $entity = new Address();
    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);

    // Inserted new code for deserialization
    $entity->setUseruid($request->request->get("useruid"));
    $entity->setCity($request->request->get("city"));
    $entity->setLatitude($request->request->get("latitude"));
    $entity->setLongitude($request->request->get("longitude"));

    $serializer = JMS\Serializer\SerializerBuilder::create()->build();
    $entity = $serializer->deserialize($request->request->all(), 'Name\BundleName\Entity\Address', 'json');

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

        return $this->redirect($this->generateUrl('address_show', array('id' => $entity->getId())));
    }

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

Lets say I am using AJAX to send requests to the API and here is my code for both GET and POST respectively:

        $.ajax({
            dataType: "json",
            type: "GET",
            url: "/symfony/web/app_dev.php/address/",
            success: function (responseText)
            {
                alert("Request was successful, data received: " + responseText); 
            },
            error: function (error) {
                alert(JSON.stringify(error));
            }
        });

        $.ajax({
            dataType: "json",
            type: "POST",
            data: {"id":1,"useruid":"Nothing","type":"Office in Space","latitude":"74.3","longitude":"33.2","displayed":true,"public":true,"verified":true,"street":"Something","city":"Something","country":"Space","region":"North America","created":"2009-03-07T00:00:00-0500","delete_status":"active"},
            url: "/symfony/web/app_dev.php/address/",
            success: function (responseText)
            {
                console.log("Request was successful, data received: " + JSON.stringify(responseText)); 

            },
            error: function (error) {
                alert(JSON.stringify(error));
            }
        });

While GET returns the correct, POST returns the following error: {"code":500,"message":"Warning: json_encode(): recursion detected in /var/www/projects/symfony/vendor/jms/serializer/src/JMS/Serializer/JsonSerializationVisitor.php line 29"}. What do I need to do resolve the error? I can return a single entity or all entities but POST which is just to send data to the path to create the entity gives the error. I have updated my JMSSerializer bundle from 0.12.* to dev-master and also checked to be sure that no NULL values are in the data to be sent by AJAX but the error remains. How can I make my POST controller create data from the valid JSON sent to it in a POST?

I also tried PUT and the result was the same and it does not update the resource, shouldn't just update the record in the table? Let me know if I need to provide any more information to figure out the source of this bug! Code has been edited above.

Upvotes: 0

Views: 966

Answers (1)

praxmatig
praxmatig

Reputation: 263

$this->redirect returns the RedirectResponse object which is not what you want. If you want to return a redirect url, simply return array('redirect_url' => $this->generate(...)) and then redirect the client with javascript.

Upvotes: 0

Related Questions