0

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();
    }
}

1 Answer 1

1

Seem that $this->getProduct() or getRelatedProductCollection()returns null value. You need to check this.

For example:

if($this->getProduct() != null)
3
  • If I wrap getRelatedProducts() code with this if statement then it works. Why though? Shouldn't my template work only when there are related products to display?
    – rits
    Feb 6, 2017 at 5:50
  • @Rudolph This is because $this->getProduct() or getRelatedProductCollection() may return null value. We need to check these value. Feb 6, 2017 at 14:51
  • $relatedProduct->getPrice(); is returning 0 price Nov 9, 2018 at 12:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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