1

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

3

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));
| improve this answer | |
3

@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.
}
| improve this answer | |
  • yes this is basically correct answer instead to inject factory over repository. User repository if available as they are basically service contracts – Hassan Ali Shahzad Jan 27 '19 at 11:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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