有没有办法让块服务获取调用它的页面 ID?

Is there a way for a block service to get the page ID from which it is being called?

在我的 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

这是可能的,但您需要在您的区块中注入额外的服务 - 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',
    ));
}

感谢 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);
}

再次感谢所有参与者。