Search code examples
symfonydoctrine-ormsymfony-sonata

Symfony: Services when using entity


I have got a services.yml in my bundle like below.

parameters:
     application_stock.admin.stocklevels: Application\StockBundle\Admin\StockLevelView
#    application_stock.example.class: Application\StockBundle\Example

services:
#    application_stock.example:
#        class: %application_stock.example.class%
#        arguments: [@service_id, "plain_value", %parameter%]
     application_stock:
         class: "%application_stock.admin.stocklevels%"
         tags:
             - { name: sonata.admin, manager_type: orm, group: application_stock, label: stock }
         arguments: [ '', Application\StockBundle\Entity\StockLevels, ApplicationStockBundle:StockLevels ]

but when I am trying to change services to

- @security.context
- { null, Application\StockBundle\Entity\StockLevels, ApplicationStockBundle:StockLevels }

then it is showing me an error

ContextErrorException: Notice: Undefined offset: 2 in C:\wamp\www\test\vendor
\sonata-project\admin-bundle\Sonata\AdminBundle\DependencyInjection\Compiler\
AddDependencyCallsCompilerPass.php line 48

Could any one please help me to solve that problem, please?

EDIT:

After adding

calls:
    - [setContainer, [@service_container]]
    - [setSecurityContext, [@security.context]]

I am getting error:

Call to a member function getUser() on a non-object in

StockLevelView.php:

<?php
namespace Application\StockBundle\Admin;

use Application\StockBundle\Entity\StockLevels;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Show\ShowMapper;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;

use Knp\Menu\ItemInterface as MenuItemInterface;

class StockLevelView extends Admin implements ContainerAwareInterface
{

/**
 * @var ContainerInterface
 */
private $container;

private $adminId;

/**
 * {@inheritDoc}
 */
public function setContainer(ContainerInterface $container = null)
{
    $this->container = $container;
}

public function setSecurityContext($securityContext)
{
    $this->adminId = $securityContext->getToken()->getUser();
}

...rest of code

Solution

  • Just use it like this:

    application_stock:
        class: "%application_stock.admin.stocklevels%"
        tags:
            - { name: sonata.admin, manager_type: orm, group: application_stock, label: stock }
        arguments: [ '', Application\StockBundle\Entity\StockLevels, ApplicationStockBundle:StockLevels ]
        calls:
            - [setSecurityContext, [@security.context]]
    

    And create public function setSecurityContext($securityContext) { ... } setter to capture security context in your admin class.