Magento 2 – How to Set and Get Block Arguments Programmatically

blockslayoutmagento2

In layout when I create a block I can set custom arguments, for example:

<block class="Company\Module\Block\Hello" name="block_name" template="test.phtml">
    <arguments>
        <argument name="my_arg" xsi:type="string">testvalue</argument>
    </arguments>
</block>

I can later retrieve the argument like this inside the block:

$arg = $this->getMyArg();

When I create a block programatically (according to this method: link) I can set custom arguments like this:

$block = $this->frameworkViewLayout
    ->createBlock(
        "Company\Module\Block\Hello",
        "block_name",
        ['my_arg' => 'testvalue']
    )
    ->setData('area', 'frontend')
    ->setTemplate($template)
    ->toHtml();

The block is correctly created and it works perfectly. But I'm not sure how I can later retrieve the argument inside block's class. I tried to do it like this:

$arg = $this->getMyArg();

or

$arg = $this->getData('my_arg');

But it returns nothing. What did I miss?

Best Answer

If you look further in the code, in the \Magento\Framework\View\Layout\Generator\Block class, the createBlock function only adds data from the $arguements['data'] element. So, I think you should change your code to this:

$block = $this->frameworkViewLayout
    ->createBlock(
        "Company\Module\Block\Hello",
        "block_name",
        [
            'data' => [
                'my_arg' => 'testvalue'
            ]
        ]
    )
    ->setData('area', 'frontend')
    ->setTemplate($template)
    ->toHtml();

Then you could use getMyArg() or getData('my_arg').