Search code examples
phpsymfonydoctrinesonatasymfony-3.3

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


In my Symfony 3.3 application, I have built a block service using SonataBlockBundle. Now I want to pull some other field values from the page on which the block lives. In other words, I want to do something like this:

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',
    ));
}

Is this possible? If so, what would I put in place of someMagicalMethodCall in the block above?


Solution

  • Thanks to Jakub Krawczyk and a mentor, I found this page:

    Getting instance of container in custom sonata block

    ... which led me to another way of getting the page related to a block, from within the execute() method. So I now have the following code, which serves me well:

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

    Again, thanks to all involved.