productRepository = $productRepository; parent::__construct($context, $customerSession); } /** * @return \Magento\Framework\Controller\Result\Redirect */ public function execute() { $productId = (int)$this->getRequest()->getParam('product'); /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (!$productId) { $resultRedirect->setPath('/'); return $resultRedirect; } try { $product = $this->productRepository->getById($productId); if (!$product->isVisibleInCatalog()) { throw new NoSuchEntityException(); } $model = $this->_objectManager->create(\Magento\ProductAlert\Model\Stock::class) ->setCustomerId($this->customerSession->getCustomerId()) ->setProductId($product->getId()) ->setWebsiteId( $this->_objectManager->get(\Magento\Store\Model\StoreManagerInterface::class) ->getStore() ->getWebsiteId() ) ->loadByParam(); if ($model->getId()) { $model->delete(); } $this->messageManager->addSuccess(__('You will no longer receive stock alerts for this product.')); } catch (NoSuchEntityException $noEntityException) { $this->messageManager->addError(__('The product was not found.')); $resultRedirect->setPath('customer/account/'); return $resultRedirect; } catch (\Exception $e) { $this->messageManager->addException( $e, __("The alert subscription couldn't update at this time. Please try again later.") ); } $resultRedirect->setUrl($product->getProductUrl()); return $resultRedirect; } }