Published on

Posting data to Symfony2


After struggling for a couple of hours I found out why my POST call to our Symphony2 backend was seemingly not working.

     * @var Request $request
     * @Rest\View()
    public function postCustomersAction(Request $request) {
        $customer = new Customer();
        $form = $this->createForm('customer', $customer);
        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();

            $data = array("id" => $customer->getId());

            $view = $this->view($data, Codes::HTTP_CREATED)
        } else {
            $data = array("errors" => $form->getErrorsAsString());
            $view = $this->view($data, Codes::HTTP_BAD_REQUEST)
        return $this->handleView($view);

all was nice and good, but when posting from both phpunit and rest client I had no luck getting any data into the form.

I was sure all data was correct, inspected the http request headers and found that the body was post in the following fashion: {"name":"test", "number":"4343"}. Then I came to the idea that the data might have to be wrapped to identify the type of the object. This resulted in instant success. I wrote the following unit test.

   public function testPostCustomer()
        $client = static::createClient();
            array("customer" =>
                    "name" => "lifely",
                    "number" => "1010"

        $response = $client->getResponse();
        $data = json_decode($response->getContent(), true);

        $this->assertEquals(Codes::HTTP_CREATED, $response->getStatusCode());
        $this->assertArrayHasKey("id", $data);