问题描述
我正在为仪表板创建一个自定义块,我想在其中显示保存在数据库中的信息.如何在块服务中获取容器或条令实体管理器的实例?
I am creating a custom block for dashboard and where I want to display information persisted into the DB. How do I get an instance of the container or doctrine entity manager in the block service?
尝试了很多谷歌搜索,但到目前为止没有任何实质性的结果
Tried googling alot but nothing substantial has come out so far
推荐答案
在 Sonata 中创建新块时,必须像服务一样声明它,这样才能注入 doctrine.orm.entity_manager
.我可以向您展示我注入实体管理器的块示例:
When you create a new block in sonata, you have to declare it like a service, so you can inject doctrine.orm.entity_manager
.I can show you an example of a block where I injected the 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 中声明您阻止并注入您需要的任何内容:
Declare you block in services.yml and inject whatever you need:
//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
Declare you block in 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: ~
然后,当然,您必须为块创建模板:
And then, of course, you have to create the template for block:
{# myblock.html.twig #}
{% extends 'SonataBlockBundle:Block:block_base.html.twig' %}
{% block block %}
<p>{{ data }}</p>
{% endblock %}
这篇关于在自定义奏鸣曲块中获取容器实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!