Search code examples
phpsymfonyfosrestbundle

Unknown key "data" for annotation "@FOS\RestBundle\Controller\Annotations\View"


I am creating simple symfony api with react app as front-end. It is supposed to create users (only usernames) and products (name and price). When I create new user it is fine. However if I decide to create new product the same way it gives an error

Unknown key "data" for annotation "@FOS\RestBundle\Controller\Annotations\View"

Here is my code in ProductController

/**
 * Creates a new product entity.
 * @Rest\Post("/post")
 */
function newAction(Request $request ) {
    $product = new Product();
    $body = $request->getContent();
    $body = str_replace('"', '"', $body);
    $body = json_decode($body, true);
    $productName = $body['name'];
    $productPrice = $body['price'];
    $product->setName($productName);
    $product->setPrice($productPrice);
    $em = $this->getDoctrine()->getManager();
    $em->persist($product);
    $em->flush();
    $data['data'] = $product;
    return new View($data,Response::HTTP_CREATED);
}

If I use the same logic and response for the user it works fine.Here is the code in UserController

 /**
 * Creates a new user entity.
 * @Rest\Post("/post")
 */
function newAction(Request $request ) {
    $user = new User();
    $body = $request->getContent();
    $body = str_replace('"', '"', $body);
    $body = json_decode($body, true);
    $username = $body['username'];
    $user->setUsername($username);
    $em = $this->getDoctrine()->getManager();
    $em->persist($user);
    $em->flush();
    $data['data'] = $user;
    return new View($data,Response::HTTP_CREATED);
}

Now my problem - the creation of new User is just fine. The creation of new Product breaks. The code is as similar as possible. Any ideas why it doesn't work?


Solution

  • [SOLVED] This is one of the stupidest mistakes I have ever made. While using View class I have pressed Alt+Enter to use it automatically. However it seems that in UserController it was using the right View class and in ProductController it used something else.