How do I get the current product?
Although other answers are correct, they're not the recommended/proper solution either.
Using the ObjectManager is absolutely prohibited in Magento 2. So please don't rely on this solution, but use proper DI to achieve this instead. To learn how to use DI in Magento 2, see this resource: http://devdocs.magento.com/guides/v2.0/extension-dev-guide/depend-inj.html
Extending AbstractView is not necessary. If you look at the original function in the AbstractView, you can see Magento used the registry to fetch the product. You don't need to extend a specific class to do this, simply inject Magento\Framework\Registry into your constructor and request the "product" registry item.
Full code example:
<?php
// Example = Module namespace, Module = module name, rest of the namespace is just for example only, change this to whatever it is in your case.
namespace Example\Module\Block\Frontend\Catalog\Product\General;
use Magento\Catalog\Model\Product;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Registry;
use Magento\Framework\View\Element\Template;
class Information extends Template
{
/**
* @var Registry
*/
protected $registry;
/**
* @var Product
*/
private $product;
public function __construct(Template\Context $context,
Registry $registry,
array $data)
{
$this->registry = $registry;
parent::__construct($context, $data);
}
/**
* @return Product
*/
private function getProduct()
{
if (is_null($this->product)) {
$this->product = $this->registry->registry('product');
if (!$this->product->getId()) {
throw new LocalizedException(__('Failed to initialize product'));
}
}
return $this->product;
}
public function getProductName()
{
return $this->getProduct()->getName();
}
}
In order to get the current product, one of the recommended ways is:
- Extend or use block class:
Magento\Catalog\Block\Product\View\AbstractView
. - Get product using:
$block->getProduct()
in your phtml file.
If you are using Magento 2.1 or major, you can use this helper
because the old method was deprecated.
...
use Magento\Catalog\Helper\Data;
...
public function __construct(
Context $context,
Data $helper,
array $data = []
){
$this->context = $context;
$this->helper = $helper;
$this->data = $data;
parent::__construct($context, $data);
}
...
public function getProduct(){
if(is_null($this->_product)){
$this->_product = $this->helper->getProduct();
}
return $this->_product;
}