With this code you create this block and render it immediately, without adding it to the layout hierarchy. That means it doesn't have access to the parent block because there is no parent.
To create a block dynamically as child of the current block, use:
$child = $this->getLayout()->createBlock("Magento\Framework\View\Element\Template")->setTemplate("Namespace_Module::state.phtml");
$this->addChild('state', $child);
And to render it:
echo $this->getChildHtml('state');
(I used "state" as alias here, but it can be anything else)
Now you have access to the parent from your state.phtml template, using $this->getParentBlock()
If I set state.phtml
in country.phtml
like
<?php
echo $this->getLayout()->createBlock("Namespace\Module\Block\Country")->setTemplate("Namespace_Module::state.phtml")->toHtml();
?>
Then Is it possible to call functions of Country.php
in
State.phtml
file ?
If you insist, you can do it like this:
echo $this->getLayout()
->createBlock("Namespace\Module\Block\Country")
->setTemplate("Namespace_Module::state.phtml")
->setData('country_block', $this)
->toHtml();
And then, in state.phtml
:
$this->getData('country_block')->METHOD_OF_COUNTRY_BLOCK();
Best Answer
Pretty sure it's possible.
What you can do first is add a protected variable to your block class:
Then you can define a public method to retrieve this variable:
Then in your controller action method you can do the following:
Please note that you'll have to replace
block.name
with the name of the block declared in your layout.