Home » Design » HTML » Access a variable declared in a phtml from another phtml in Magento2

Access a variable declared in a phtml from another phtml in Magento2

posted in: Design, HTML, PHP, Programming, XML 0

Having two blocks in the catalog_product_view.xml file like this:

<block class="Magento\Catalog\Block\Product\View" name="product.info.custom-product-attributes" template="product/view/custom-product-attributes.phtml" after="product.info.overview"/>
...
<block class="Magento\Catalog\Block\Product\View" name="product.info.custom-estimated-delivery" template="product/view/custom-estimated-delivery.phtml" after="product.price.final"/>

To access a variable declared in the first block from the second block, you can set the variable with register from the first phtml, then you get the value in the 2nd phtml with registry

To do things well without injecting direclty the objectManager in phtml, you have to create some function your product block, so in your block : app/code/Vendor/Modulename/Block/Custom.phpassuming that your variable name is : $tech add the following code:

<?php
namespace Vendor\Modulename\Block;

class Custom extends \Magento\Framework\View\Element\Template
{
    protected $_coreRegistry;

    public function __construct(
        ...
        \Magento\Framework\Registry $coreRegistry
    ) {
        ...
        $this->_coreRegistry = $coreRegistry;
    }

    /**
     * Set var data
     */
    public function setTechData($data)
    {
        $this->_coreRegistry->register('tech', $data);
    }

    /**
     * Get var data
     */
    public function getTechData()
    {
        return $this->_coreRegistry->registry('tech');
    }
}

Then in your First phtml :


<?php $tech = 'Your Data here'; ?>
<?php $block->setTechData($tech); ?>

Then, in the Second phtml :

<?php $block->getTechData(); ?> //you'll get your tech value here

Besides, you can also do that in phtml to test without the block solution,

First phtml :

<?php 
$tech = 'Your Data here';
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$objectManager->create("Magento\Framework\Registry")->register('tech', $tech);
?>

Second phtml :

<?php 
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$techData = $objectManager->create("Magento\Framework\Registry")->registry('tech');
echo $techData;
?>

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.