Some colleagues and I are using Sonata Block Bundle in combination with Sonata Page Bundle. In our interface, we are able to open a page, then add blocks to it. Simple.
Now I want to send emails that include the page title and the first text block related to the page. I use dump($page)
in my controller to verify that I have access to the page. I pull the title from the page via $page->getTitle()
.
But when I try to retrieve block information, the $page->getBlocks()
method just returns an object containing an empty collection.
I have verified that I can load the blocks from the page in the CMS, so I know there's a way to do it.
What am I doing wrong?
The $blocks
parameter of the Page
entity is a realation, therefore by default is is lazy loaded.
If you want to have $block
always loaded when you load any Page
entity anywhere, you can eager load blocks, this is however not recommended due to performance impact (you probably don't need $blocks
every time you load Page
entity).
Another way if having the $blocks
loaded is to initialize the collection manually, like so:
$blocks = $page->getBlocks();
$blocks->initialize();
Then, when you dump($blocks)
they should not be an empty collection.
In general the lazy fetched collections are initialized on the moment they are used, e.g. in a foreach - that's why it worked.