kalites
kalites

Reputation: 69

symfony SerializerInterface serializer argument

i'm using the last version of symfony 3.3

i'm trying to return json but i get an error

this is my controller:

<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Serializer\SerializerInterface;

class ApiController extends Controller{
    /**
     * @Route("home", name="api_home")
     */
    public function indexAction(SerializerInterface $serializer)
    {
        $entity = $this->getDoctrine()
            ->getRepository('AppBundle:User')
            ->findAll();
        $json = $serializer->serialize($entity,'json', ['groups' => ['User']]);
        return new JsonResponse($json, 200, [], true);
    }
}

on services.yml:

services:
  _defaults:
      public: false
      autowire: false
      autoconfigure: true

config.yml

serializer:
    enabled: true
    enable_annotations: true

i'm getting error:

Controller "AppBundle\Controller\ApiController::indexAction()" requires that you provide a value for the "$serializer" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one.

i try do die before $json

but same error

thanks

Upvotes: 1

Views: 2659

Answers (2)

kalites
kalites

Reputation: 69

it's happen just because i didn't have this on services.yml

  AppBundle\Controller\:
        resource: '../../src/AppBundle/Controller/*'
        public: true
        tags: ['controller.service_arguments']

Upvotes: 3

Matteo
Matteo

Reputation: 39380

The action method can have Request attribute or params converted from the request (the service you need you should retrieve from the container) so try the following code:

/**
 * @Route("home", name="api_home")
 */
public function indexAction()
{
    $serializer = $this->get('serializer');
    $entity = $this->getDoctrine()
        ->getRepository('AppBundle:User')
        ->findAll();
    $json = $serializer->serialize($entity,'json', ['groups' => ['User']]);
    return new JsonResponse($json, 200, []);
}

Hope this help

Upvotes: 0

Related Questions