在我的Symfony 3.3应用程序中,我使用SonataBlockBundle构建了一个块服务。现在我想从块所在的页面中提取其他一些字段值。换句话说,我想做这样的事情:
public function configureSettings(OptionsResolver $resolver)
{
$pageRepository = $this->doctrine->getRepository('ApplicationSonataPageBundle:Page');
$pageId = someMagicalMethodCall();
$page = $repository->findOneBy(['id' => $pageId]);
$images = $page->getImageUrls;
$resolver->setDefaults(array(
'content' => 'Some custom content',
'images' => $images,
'template' => 'AppBundle:Block:block_media.html.twig',
));
}
这可能吗?如果是这样,我会在上面的块中代替someMagicalMethodCall
?
答案 0 :(得分:1)
有可能,但您需要在您的区块中注入其他服务 - CmsManagerSelector
。然后在configureSettings
中,您需要检索正确的经理并从中获取当前页面实例。例如,在您的代码中:
public function configureSettings(OptionsResolver $resolver)
{
$cmsManager = $this->cmsManagerSelector->retrieve();
// $page will be the Page object already, no need to call doctrine repository. Reference: https://github.com/sonata-project/SonataPageBundle/blob/3.x/src/CmsManager/BaseCmsPageManager.php#L38
$page = $cmsManager->getCurrentPage();
$images = $page->getImageUrls;
$resolver->setDefaults(array(
'content' => 'Some custom content',
'images' => $images,
'template' => 'AppBundle:Block:block_media.html.twig',
));
}
答案 1 :(得分:0)
感谢Jakub Krawczyk和导师,我找到了这个页面:
Getting instance of container in custom sonata block
...这让我想到了另一种从execute()方法中获取与块相关的页面的方法。所以我现在有以下代码,这对我很有帮助:
public function execute(BlockContextInterface $blockContext, Response $response = null)
{
$page = $blockContext->getBlock()->getPage();
$localImages = $page->getImages();
$imageProvider = $this->provider;
foreach ($localImages as $key => $image) {
$publicImages[$key]['url'] = $imageProvider->generatePublicUrl($image, 'reference');
$publicImages[$key]['name'] = $image->getName();
}
$settings = $blockContext->getSettings();
$settings['images'] = $publicImages;
return $this->renderResponse($blockContext->getTemplate(), array(
'block' => $blockContext->getBlock(),
'settings' => $settings,
), $response);
}
再次感谢所有参与者。