Search code examples
phpsymfonydependency-injectionsonata-adminphp-5.5

Right way to inject container service in Sonata Admin Bundle


I'm trying to inject the service container in my Sonata Admin class in order to use it at configureFormFields method. This is what I have:

config.yml (sonata services definition)

services:
  tan.product.admin.product:
    class: Tan\ProductBundle\Admin\ProductAdmin
    tags:
      - { name: sonata.admin, manager_type: orm, group: Product, label: Product }
    arguments: [ null, Tan\ProductBundle\Entity\Product, @service_container]

ProductAdmin.php

class ProductAdmin extends Admin
{

    /** @var \Symfony\Component\DependencyInjection\ContainerInterface */
    private $container;
    public $supportsPreviewMode = true;

    /**
     * @param string $code
     * @param string $class
     * @param string $baseControllerName
     */
    public function __construct($code, $class, $baseControllerName, $container = null)
    {
        parent::__construct($code, $class, $baseControllerName);
        $this->container = $container;
    }

    // other methods 

    protected function configureFormFields(FormMapper $form)
    {

        $helper = $this->container->get('oneup_uploader.templating.uploader_helper');
        $endpoint = $helper->endpoint('products');

        $form
                ->add('product_name', null, array('label' => 'Nombre'))
                ->add('product_description', null, array('label' => 'Descripción'));
    }

}

But I'm getting this error:

ContextErrorException: Catchable Fatal Error: Object of class appDevDebugProjectContainer could not be converted to string in /var/www/html/tan/var/cache/dev/classes.php line 12979

What's wrong there?


Solution

  • Since your constructor takes 4 arguments where the 4th is the service container, you need to pass in the service container 4th:

    services:
      tan.product.admin.product:
      class: Tan\ProductBundle\Admin\ProductAdmin
      tags:
          - { name: sonata.admin, manager_type: orm, group: Product, label: Product }
      arguments: [ null, Tan\ProductBundle\Entity\Product, null, @service_container]