1

I added new block to load my custom phtml inside catalog view,the problem is i need to load the current product model at my phtml, but i don't know how to do it.

app/code/Namespace/Module/view/frontend/layout/catalog_product_view.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
  <body>
    <referenceBlock name="product.info.social">
        <block class="Namespace\Module\Block\Custom" name="custom.product.view" template="Namespace_Module::custom.phtml"> </block>
    </referenceBlock>
  </body>
</page>
2

There are two way you can current product object at your custom class

First

using registry variable, In product details at every block section, you get forestry variable current_product .

Inject the registry class on you class __construct() function

 /**
 * Core registry
 *
 * @var \Magento\Framework\Registry
 */
protected $_coreRegistry;

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

/**
 * Retrieve current product object
 *
 * @return \Magento\Catalog\Model\Product
 */
public function getProduct()
{
    return $this->_coreRegistry->registry('current_product');
}

Second

second, once extends \Magento\Catalog\Block\Product\View which @keyur already explained

|improve this answer|||||
1

Adding from the @Amit answer, If you are creating a new block (As you mentioned in question Namespace\Module\Block\Custom) then just extend your block class with \Magento\Catalog\Block\Product\View. Now you can access $product object in phtml file like $block->getProduct()

|improve this answer|||||
  • Ha ha , that i will going to add.. – Amit Bera Jan 11 '18 at 7:54
  • 1
    Yes, I think its simplest answer just extend the class and you have all properties of $product object :) @AmitBera – Keyur Shah Jan 11 '18 at 7:57
  • Ya, it is depends on devloper call, If his/her class already extends another then they must use registry.other wise your solution is super – Amit Bera Jan 11 '18 at 8:00
  • Yes, I agree with you registry is the best option to get $product object anywhere , +1 for your efforts :) @AmitBera – Keyur Shah Jan 11 '18 at 8:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.