7

In Magento 1, if you wanted to programmatically add a new block to the text/list content block, you could do something like this

$block = $this->getLayout()->getBlock('content');
$block->append($this->getLayout()->createBlock('foo/baz'));

However, in Magento 2, this doesn't work. Calling something like

$block = $this->getLayout()->getBlock('content');

returns a value of false into the $block variable. I'm relatively sure this is because content is no longer a block -- it's something Magento 2 calls a container.

Is it possible, via PHP, to get a reference to these containers and programmatically add blocks to them?

I know it's possible to do this via the new Layout DSL with something like

<body>
    <referenceContainer name="content">
        <block ... />
    </reference>
</body>

What I want to know is if this is possible to do via PHP, or if PHP level access to the container blocks not possible (either by deliberate or defacto design). If it is possible -- what are the objects and methods involved?

7

Containers are partially like blocks, they have a name and so on, but you cant access them directly over the layout component. But still, you can (if they allow) modify them(but no idea in which context this is important)

What you are searching for I think is the ->layout()->addBlock(...) method, which has a parent as 3. argument.

This may not work from everywhere, actually I did it only test from one place, where it did not work. Hope it still helps

1
  • 1
    This helped, thanks! Also, for anyone coming along later, it looks like the current addBlock has bug it will try to create a structure element or block even if you pass in a block object.
    – Alan Storm
    Sep 11 '15 at 0:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.