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();
You have to first override block for add new function in sidebar.php file.
You cant use plugin method for add new function in block file.
You can use plugin method to overrider already defined public function in file.
You must have to overrider sidebar.php file and add new function inside sidebar.php file after adding function you can call those function inside your template file.
under
Vendor/Modulename/etc/di.xml
file,
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Checkout\Block\Cart\Sidebar" type="Vendor/Modulename/Block/Cart/Sidebar" />
</config>
Inside sidebar.php file,
Vendor/Modulename/Block/Cart/Sidebar.php
you can define your new function.
Best Answer
Add below code in js file:
Add below code in template file: