Magento – Call to a member function getId() on null – module-catalog/Helper/Product.php

magento2

I added sample data to my magento2 website, but when I want to access to a product I always get this error :

Fatal error: Uncaught Error: Call to a member function getId() on null
in
/var/www/html/test/vendor/magento/module-catalog/Helper/Product.php:313
Stack trace: #0
/var/www/html/test/vendor/magento/module-catalog/Helper/Product.php(430):
Magento\Catalog\Helper\Product->canShow(NULL) #1
/var/www/html/test/vendor/magento/module-catalog/Helper/Product/View.php(263):
Magento\Catalog\Helper\Product->initProduct(1562,
Object(Magento\Catalog\Controller\Product\View\Interceptor),
Object(Magento\Framework\DataObject)) #2
/var/www/html/test/vendor/magento/module-catalog/Controller/Product/View.php(118):
Magento\Catalog\Helper\Product\View->prepareAndRender(Object(Magento\Framework\View\Result\Page\Interceptor),
1562, Object(Magento\Catalog\Controller\Product\View\Interceptor),
Object(Magento\Framework\DataObject)) #3
/var/www/html/test/vendor/magento/framework/App/Action/Action.php(108):
Magento\Catalog\Controller\Product\View->execute() #4
/var/www/html/test/vendor/magento/framework/Interception/Interceptor.php(58):
Magento\Framewor in
/var/www/html/test/vendor/magento/module-catalog/Helper/Product.php on
line 313

The Product.php code :

public function canShow($product, $where = 'catalog')
    {
        if (is_int($product)) {
            try {
                $product = $this->productRepository->getById($product);
            } catch (NoSuchEntityException $e) {
                return false;
            }
        } else {
       /*313*/     if (!$product->getId()) {
                return false;
            }
        }
        return $product->isVisibleInCatalog() && $product->isVisibleInSiteVisibility();
    }

when I var_dump($product) it's return NULL

Product.php class code : https://snipsave.com/saadsaad/#/snippet/iDIEafixLtWgzWO9sK

is there any solution?

Best Answer

After a lot of search, I found that the problem was on di.xml

because I added this:

<preference for="Magento\Catalog\Api\ProductRepositoryInterface" 
        type="Testing\HelloWorld\Model\CustomImplementation" />

so I remove it and it's work