在自定义奏鸣曲块中获取容器的实例

时间:2014-06-15 11:29:54

标签: symfony sonata-admin

我正在为仪表板创建一个自定义块,我想在其中显示持久存储到数据库中的信息。如何在块服务中获取容器或doctrine实体管理器的实例?

尝试使用谷歌搜索,但到目前为止没有任何实质内容发布

1 个答案:

答案 0 :(得分:9)

在sonata中创建新块时,必须将其声明为服务,因此可以注入doctrine.orm.entity_manager。 我可以向您展示我注入实体管理器的块的示例:

//My\Bundle\Block\MyBlockService

use Symfony\Component\HttpFoundation\Response;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Validator\ErrorElement;
use Sonata\BlockBundle\Model\BlockInterface;
use Sonata\BlockBundle\Block\BaseBlockService;
use Sonata\BlockBundle\Block\BlockContextInterface;

class MyBlockService extends BaseBlockService
{
    protected $em;

    public function __construct($type, $templating, $em)
    {
        $this->type = $type;
        $this->templating = $templating;
        $this->em = $em;
    }

    public function getName()
    {
        return 'MyBlock';
    }

    public function getDefaultSettings()
    {
        return array();
    }

    public function validateBlock(ErrorElement $errorElement, BlockInterface $block)
    {
    }

    public function buildEditForm(FormMapper $formMapper, BlockInterface $block)
    {
    }

    public function execute(BlockContextInterface $blockContext, Response $response = null)
    {
        $settings = array_merge($this->getDefaultSettings(), $blockContext->getBlock()->getSettings());

        $data = count($this->em->getRepository("MyBundle:Entity")->findAll());

        return $this->renderResponse('MyBundle::myblock.html.twig', array(
            'block' => $blockContext->getBlock(),
            'settings' => $settings,
            'data' => $data,
        ), $response);
    }
}

声明你在services.yml中阻止并注入你需要的东西:

//services.yml
sonata.block.service.myblock:
        class: My\Bundle\Block\MyBlockService
        arguments: [ "sonata.block.service.myblock", @templating, @doctrine.orm.entity_manager ]
        tags:
            - { name: sonata.block }

声明你在config.yml中阻止:     //config.yml

sonata_block:
    default_contexts: [cms]
    blocks:
    # Enable the SonataAdminBundle block
    sonata.admin.block.admin_list:
        contexts:   [admin]
    sonata.block.service.myblock: ~

然后,当然,您必须为块创建模板:

{# myblock.html.twig #}
{% extends 'SonataBlockBundle:Block:block_base.html.twig' %}


{% block block %}
   <p>{{ data }}</p>
{% endblock %}