Magento 2 - Product get id by sku - non existent product causes error
-
10-10-2020 - |
Question
I am writing a module that takes a users input of product SKU (via a form) and then adds to the cart.
The issue I'm having is that when I am testing by using a non existent SKU the exception that is thrown can not be caught and leads to an exception on page.
Ideally I want to be able to catch the exception and display as a nice message to the user.
In my controller I am getting the product like so:
<?php
public function __construct(Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Magento\Checkout\Model\Cart $cart,
\Magento\Catalog\Model\ProductRepository $productRepository)
{
$this->_resultPageFactory = $resultPageFactory;
$this->_cart = $cart;
$this->_productRepository = $productRepository;
parent::__construct($context);
}
public function execute()
{
$postParams = $this->getRequest()->getParams();
// ... extract SKU process removed for clarity.
//////// HERE IS THE ISSUE ////////////////
try{
$p = $this->_productRepository->get($sku);
}catch(Exception $e){
// this isn't caught, but outputed to the browser
$errMsg = 'error: '.$e->getMessage();
}
}
?>
Is there another way I can determine if a product SKU exists?
Thanks
Solution
Instead of using the ProductRepository , inject the ProductFactory:
public function __construct(\Magento\Catalog\Model\ProductFactory $productFactory)
{
$this->productFactory = $productFactory;
}
and load like this:
$product = $this->productFactory->create();
$product->load($product->getIdBySku($sku));
OTHER TIPS
@sulman, you can use searchCriteriaBuilder to filter based on SKU.
you can use this code to check SKU availability.
Include this class in your constructor.
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder;
Add this below logic in your execute function.
$searchCriteria = $this->searchCriteriaBuilder->addFilter("sku", '87283', 'eq')->create();
$products = $this->_productRepository->getList($searchCriteria);
$Items = $products->getItems();
if (count($Items) == 0) {
// your customer message here.
}