I get this error when I go to any page where there aren't any related products displayed.
Error:
( ! ) Fatal error: Uncaught Error: Call to a member function getRelatedProductCollection() on null in C:\wamp64\www\magento2\app\code\Test\RelatedProducts\Block\Product.php on line 88
Method where line 88 is located:
public function getRelatedProducts()
{
$relatedProducts = $this
->getProduct()
->getRelatedProductCollection()
->addAttributeToSelect(['price','name','image','status']);
return $relatedProducts;
}
Constructor:
public function __construct(
StoreManagerInterface $storeManager,
Currency $currency,
Context $context,
Registry $registry,
array $data = []
) {
$this->_storeManager = $storeManager;
$this->_currency = $currency;
$this->_registry = $registry;
parent::__construct($context, $data);
}
EDIT:
If I add if($this->getProduct() != null)
to getRelatedProducts() then everything is fine.
/**
* Return current product
*
* @return mixed
*/
public function getProduct()
{
return $this->_registry->registry('product');
}
/**
* Return collection of related products from the current product
*
* @return mixed
*/
public function getRelatedProducts()
{
if($this->getProduct() != null){
$relatedProducts = $this
->getProduct()
->getRelatedProductCollection()
->addAttributeToSelect(['price','name','image','status']);
$relatedProducts->getSelect()->orderRand();
return $relatedProducts->getItems();
}
}