代码之家  ›  专栏  ›  技术社区  ›  Mayor of the Plattenbaus

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

  •  2
  • Mayor of the Plattenbaus  · 技术社区  · 6 年前

    在我的Symfony 3.3应用程序中,我使用SonatableLockbundle构建了一个块服务。现在,我想从块所在的页面中提取一些其他字段值。换句话说,我想这样做:

    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 在上面的街区?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Jakub Krawczyk    6 年前

    这是可能的,但您需要在块中注入额外的服务- 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',
        ));
    }
    
        2
  •  0
  •   Mayor of the Plattenbaus    6 年前

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

    再次感谢所有相关人员。