There are two ways to get current product in Magento 2.
- Using custom block class extended from Magento\Catalog\Block\Product\AbstractProduct
- Using core registry.
Using custom block class:
In this method, we can extended our frontend block class i.e. Namespace/Modulename/Block/Myblock.php from Magento\Catalog\Block\Product\AbstractProduct which is a lightweight concrete class to get most product related information.
So, we can use the following code inside our custom module’s page configuration layout file which is Namespace/Modulename/view/frontend/layout/catalog_product_view.xml
<block class="Namespace\Modulename\Block\Product\View\Myblock" name="product.info.myblock" after="product.info.media.image" template="Namespace_Modulename::product/view/myblock.phtml"/>
And now in our block class Namespace/Modulename/Block/Product/View/Myblock.php we need to something like:
<?php namespace Namespace\Modulename\Block\Product\View; class Myblock extends \Magento\Catalog\Block\Product\AbstractProduct { public function __construct(\Magento\Catalog\Block\Product\Context $context, array $data = []) { parent::__construct($context, $data); } }
As we extended our module’s block from Magento\Catalog\Block\Product\View we need to add Magento_Catalog as a dependency in our module.xml file
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Namespace_Modulename" setup_version="0.0.1"> <sequence> <module name="Magento_Catalog"/> </sequence> </module> </config>
And then in our block’s template file we can do something like
$this->product = $this->getProduct()->getId();
Using core registry:
This method is normally used where a ‘single’ product object is already loaded i .e. in any template files in product page. So, if we define a block in our module’s page configuration layout file which is Namespace/Modulename/view/frontend/layout/catalog_product_view.xml and set its block type class as
Magento\Catalog\Block\Product\View, we can then use the following code in block’s template file:
$this->product = $this->_coreRegistry->registry('product');