I want to pass object as a argument from phtml file how can I do this? As I've checked we can pass string using $block->setData('var','test')
but didn't found for object.
-
May I know how you write block file?– JineshMar 17, 2020 at 9:23
-
I've created block using $block = $this->getLayout()->createBlock('') in phtml and want to pass object as a argument on that block.– Dj3Mar 17, 2020 at 9:38
2 Answers
a simple example to pass a variable from Magento (template, controller, etc) file to a block with php code.
Call a block using the createBlock() method:
<?php
echo $this->getLayout()->createBlock('module/template_name')
->setData('key', $obj)
->setTemplate('module/newblock.phtml')->toHtml();
-
Using above code we can pass xsi:type="string" argument and I want to pass xsi:type="object" argument which is not possible with above solution.– Dj3Mar 17, 2020 at 9:51
-
-
-
-
Even if this post is 3 years old I'll answer it in case someone needs the solution.
WARNING: you should never use getLayout()->createBlock
, the correct way would be creating a new <block>
inside the layout.xml. Also, you should never use ObjectManager as done in this answer, but it's the only way that I found working with the getLayout()->createBlock
instruction.
This is the solution (inside your .phtml):
<?php
// Get an instance of the class to pass to the block as argument
$obj = Bootstrap::getObjectManager()->get(ObjectClassToPassToBlock::class);
...
// Create the block passing it the object inside the param "argumentKey"
$block = $this->getLayout()->createBlock(
Block::class,
'block_name',
[
'data' => ['argumentKey' => $obj]
]
);
?>
<?= $block->toHtml(); ?>
...
Doing like this you will create a block with name block_name
and class Block::class
and you will pass it an argument of type xsi:type="object"
inside argumentKey
If you want to set the arguments of the block using the $block->setData
instruction you can do like this:
$block->setData('argumentKey', $obj);