How to get remain stock of product , if some of added in cart












1














I am just modifying magento add to cart ajax functionality.
I want to check remain quantity of product if some is added to cart.
But i tried ,many ways but i did not success.
Instead of message manager, i want to display message in popup.



I tried



<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace DevCheckoutControllerCart;

use MagentoCatalogApiProductRepositoryInterface;
use MagentoCheckoutModelCart as CustomerCart;
use MagentoFrameworkExceptionNoSuchEntityException;
use MagentoCatalogInventoryApiStockRegistryInterface;

/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Add extends MagentoCheckoutControllerCart
{
/**
* @var ProductRepositoryInterface
*/
protected $productRepository;


/**
* @param MagentoFrameworkAppActionContext $context
* @param MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
* @param MagentoCheckoutModelSession $checkoutSession
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param MagentoFrameworkDataFormFormKeyValidator $formKeyValidator
* @param CustomerCart $cart
* @param ProductRepositoryInterface $productRepository
* @codeCoverageIgnore
*/
public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig,
MagentoCheckoutModelSession $checkoutSession,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkDataFormFormKeyValidator $formKeyValidator,
MagentoCatalogInventoryApiStockStateInterface $StockStateInterface,
CustomerCart $cart,
ProductRepositoryInterface $productRepository,
StockRegistryInterface $StockRegistryInterface
) {
parent::__construct(
$context,
$scopeConfig,
$checkoutSession,
$storeManager,
$formKeyValidator,
$cart
);
$this->productRepository = $productRepository;
$this->storeManager = $storeManager;
$this->stockRegistryInterface = $StockRegistryInterface;
}

/**
* Initialize product instance from request data
*
* @return MagentoCatalogModelProduct|false
*/
protected function _initProduct()
{
$productId = (int)$this->getRequest()->getParam('product');
if ($productId) {
$storeId = $this->_objectManager->get(
MagentoStoreModelStoreManagerInterface::class
)->getStore()->getId();
try {
return $this->productRepository->getById($productId, false, $storeId);
} catch (NoSuchEntityException $e) {
return false;
}
}
return false;
}

/**
* Add product to shopping cart action
*
* @return MagentoFrameworkControllerResultRedirect
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function execute()
{
if (!$this->_formKeyValidator->validate($this->getRequest())) {
return $this->resultRedirectFactory->create()->setPath('*/*/');
}
$params = $this->getRequest()->getParams();
// Checking product quantity
$productStockObj = $this->stockRegistryInterface->getStockItem($params['product']);
$remainQty = $productStockObj->getQty();

$requestFrom = '';
if (array_key_exists('message-popup', $params)) {

try {
if (isset($params['qty'])) {
$filter = new Zend_Filter_LocalizedToNormalized(
['locale' => $this->_objectManager->get(
MagentoFrameworkLocaleResolverInterface::class
)->getLocale()]
);
$params['qty'] = $filter->filter($params['qty']);
}

$product = $this->_initProduct();
$related = $this->getRequest()->getParam('related_product');

/**
* Check product availability
*/
if (!$product) {
return $this->goBack();
}


$this->cart->addProduct($product, $params);
if (!empty($related)) {
$this->cart->addProductsByIds(explode(',', $related));
}

$this->cart->save();

/**
* @todo remove wishlist observer MagentoWishlistObserverAddToCart
*/
$this->_eventManager->dispatch(
'checkout_cart_add_product_complete',
['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()]
);

if (!$this->_checkoutSession->getNoCartRedirect(true)) {
if (!$this->cart->getQuote()->getHasError()) {
if ($this->shouldRedirectToCart()) {
$message = __(
'You added %1 to your shopping cart.',
$product->getName()
);
$this->messageManager->addSuccessMessage($message);
} else {
$this->messageManager->addComplexSuccessMessage(
'addCartSuccessMessage',
[
'product_name' => $product->getName(),
'cart_url' => $this->getCartUrl(),
]
);
}
}
return $this->goBack(null, $product);
}
} catch (MagentoFrameworkExceptionLocalizedException $e) {
if ($this->_checkoutSession->getUseNotice(true)) {
$this->messageManager->addNotice(
$this->_objectManager->get(MagentoFrameworkEscaper::class)->escapeHtml($e->getMessage())
);
} else {
$messages = array_unique(explode("n", $e->getMessage()));
foreach ($messages as $message) {
$this->messageManager->addError(
$this->_objectManager->get(MagentoFrameworkEscaper::class)->escapeHtml($message)
);
}
}

$url = $this->_checkoutSession->getRedirectUrl(true);

if (!$url) {
$url = $this->_redirect->getRedirectUrl($this->getCartUrl());
}

return $this->goBack($url);
} catch (Exception $e) {
$this->messageManager->addException($e, __('We can't add this item to your shopping cart right now.'));
$this->_objectManager->get(PsrLogLoggerInterface::class)->critical($e);
return $this->goBack();
}
}
}

/**
* Resolve response
*
* @param string $backUrl
* @param MagentoCatalogModelProduct $product
* @return $this|MagentoFrameworkControllerResultRedirect
*/
protected function goBack($backUrl = null, $product = null)
{
if (!$this->getRequest()->isAjax()) {
return parent::_goBack($backUrl);
}

$result = ;

if ($backUrl || $backUrl = $this->getBackUrl()) {
$result['backUrl'] = $backUrl;
} else {
if ($product && !$product->getIsSalable()) {
$result['product'] = [
'statusText' => __('Out of stock')
];
}
}

$this->getResponse()->representJson(
$this->_objectManager->get(MagentoFrameworkJsonHelperData::class)->jsonEncode($result)
);
}

/**
* @return string
*/
private function getCartUrl()
{
return $this->_url->getUrl('checkout/cart', ['_secure' => true]);
}

/**
* @return bool
*/
private function shouldRedirectToCart()
{
return $this->_scopeConfig->isSetFlag(
'checkout/cart/redirect_to_cart',
MagentoStoreModelScopeInterface::SCOPE_STORE
);
}
}


I used
MagentoCatalogInventoryApiStockRegistryInterface;
function getStockItem();



But i m not getting the remain stock of product.
I need to validate product stock before add to cart, and if not stock display no stock in popup.










share|improve this question







New contributor




DEEPAK KUMAR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

























    1














    I am just modifying magento add to cart ajax functionality.
    I want to check remain quantity of product if some is added to cart.
    But i tried ,many ways but i did not success.
    Instead of message manager, i want to display message in popup.



    I tried



    <?php
    /**
    *
    * Copyright © Magento, Inc. All rights reserved.
    * See COPYING.txt for license details.
    */
    namespace DevCheckoutControllerCart;

    use MagentoCatalogApiProductRepositoryInterface;
    use MagentoCheckoutModelCart as CustomerCart;
    use MagentoFrameworkExceptionNoSuchEntityException;
    use MagentoCatalogInventoryApiStockRegistryInterface;

    /**
    * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
    */
    class Add extends MagentoCheckoutControllerCart
    {
    /**
    * @var ProductRepositoryInterface
    */
    protected $productRepository;


    /**
    * @param MagentoFrameworkAppActionContext $context
    * @param MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
    * @param MagentoCheckoutModelSession $checkoutSession
    * @param MagentoStoreModelStoreManagerInterface $storeManager
    * @param MagentoFrameworkDataFormFormKeyValidator $formKeyValidator
    * @param CustomerCart $cart
    * @param ProductRepositoryInterface $productRepository
    * @codeCoverageIgnore
    */
    public function __construct(
    MagentoFrameworkAppActionContext $context,
    MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig,
    MagentoCheckoutModelSession $checkoutSession,
    MagentoStoreModelStoreManagerInterface $storeManager,
    MagentoFrameworkDataFormFormKeyValidator $formKeyValidator,
    MagentoCatalogInventoryApiStockStateInterface $StockStateInterface,
    CustomerCart $cart,
    ProductRepositoryInterface $productRepository,
    StockRegistryInterface $StockRegistryInterface
    ) {
    parent::__construct(
    $context,
    $scopeConfig,
    $checkoutSession,
    $storeManager,
    $formKeyValidator,
    $cart
    );
    $this->productRepository = $productRepository;
    $this->storeManager = $storeManager;
    $this->stockRegistryInterface = $StockRegistryInterface;
    }

    /**
    * Initialize product instance from request data
    *
    * @return MagentoCatalogModelProduct|false
    */
    protected function _initProduct()
    {
    $productId = (int)$this->getRequest()->getParam('product');
    if ($productId) {
    $storeId = $this->_objectManager->get(
    MagentoStoreModelStoreManagerInterface::class
    )->getStore()->getId();
    try {
    return $this->productRepository->getById($productId, false, $storeId);
    } catch (NoSuchEntityException $e) {
    return false;
    }
    }
    return false;
    }

    /**
    * Add product to shopping cart action
    *
    * @return MagentoFrameworkControllerResultRedirect
    * @SuppressWarnings(PHPMD.CyclomaticComplexity)
    */
    public function execute()
    {
    if (!$this->_formKeyValidator->validate($this->getRequest())) {
    return $this->resultRedirectFactory->create()->setPath('*/*/');
    }
    $params = $this->getRequest()->getParams();
    // Checking product quantity
    $productStockObj = $this->stockRegistryInterface->getStockItem($params['product']);
    $remainQty = $productStockObj->getQty();

    $requestFrom = '';
    if (array_key_exists('message-popup', $params)) {

    try {
    if (isset($params['qty'])) {
    $filter = new Zend_Filter_LocalizedToNormalized(
    ['locale' => $this->_objectManager->get(
    MagentoFrameworkLocaleResolverInterface::class
    )->getLocale()]
    );
    $params['qty'] = $filter->filter($params['qty']);
    }

    $product = $this->_initProduct();
    $related = $this->getRequest()->getParam('related_product');

    /**
    * Check product availability
    */
    if (!$product) {
    return $this->goBack();
    }


    $this->cart->addProduct($product, $params);
    if (!empty($related)) {
    $this->cart->addProductsByIds(explode(',', $related));
    }

    $this->cart->save();

    /**
    * @todo remove wishlist observer MagentoWishlistObserverAddToCart
    */
    $this->_eventManager->dispatch(
    'checkout_cart_add_product_complete',
    ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()]
    );

    if (!$this->_checkoutSession->getNoCartRedirect(true)) {
    if (!$this->cart->getQuote()->getHasError()) {
    if ($this->shouldRedirectToCart()) {
    $message = __(
    'You added %1 to your shopping cart.',
    $product->getName()
    );
    $this->messageManager->addSuccessMessage($message);
    } else {
    $this->messageManager->addComplexSuccessMessage(
    'addCartSuccessMessage',
    [
    'product_name' => $product->getName(),
    'cart_url' => $this->getCartUrl(),
    ]
    );
    }
    }
    return $this->goBack(null, $product);
    }
    } catch (MagentoFrameworkExceptionLocalizedException $e) {
    if ($this->_checkoutSession->getUseNotice(true)) {
    $this->messageManager->addNotice(
    $this->_objectManager->get(MagentoFrameworkEscaper::class)->escapeHtml($e->getMessage())
    );
    } else {
    $messages = array_unique(explode("n", $e->getMessage()));
    foreach ($messages as $message) {
    $this->messageManager->addError(
    $this->_objectManager->get(MagentoFrameworkEscaper::class)->escapeHtml($message)
    );
    }
    }

    $url = $this->_checkoutSession->getRedirectUrl(true);

    if (!$url) {
    $url = $this->_redirect->getRedirectUrl($this->getCartUrl());
    }

    return $this->goBack($url);
    } catch (Exception $e) {
    $this->messageManager->addException($e, __('We can't add this item to your shopping cart right now.'));
    $this->_objectManager->get(PsrLogLoggerInterface::class)->critical($e);
    return $this->goBack();
    }
    }
    }

    /**
    * Resolve response
    *
    * @param string $backUrl
    * @param MagentoCatalogModelProduct $product
    * @return $this|MagentoFrameworkControllerResultRedirect
    */
    protected function goBack($backUrl = null, $product = null)
    {
    if (!$this->getRequest()->isAjax()) {
    return parent::_goBack($backUrl);
    }

    $result = ;

    if ($backUrl || $backUrl = $this->getBackUrl()) {
    $result['backUrl'] = $backUrl;
    } else {
    if ($product && !$product->getIsSalable()) {
    $result['product'] = [
    'statusText' => __('Out of stock')
    ];
    }
    }

    $this->getResponse()->representJson(
    $this->_objectManager->get(MagentoFrameworkJsonHelperData::class)->jsonEncode($result)
    );
    }

    /**
    * @return string
    */
    private function getCartUrl()
    {
    return $this->_url->getUrl('checkout/cart', ['_secure' => true]);
    }

    /**
    * @return bool
    */
    private function shouldRedirectToCart()
    {
    return $this->_scopeConfig->isSetFlag(
    'checkout/cart/redirect_to_cart',
    MagentoStoreModelScopeInterface::SCOPE_STORE
    );
    }
    }


    I used
    MagentoCatalogInventoryApiStockRegistryInterface;
    function getStockItem();



    But i m not getting the remain stock of product.
    I need to validate product stock before add to cart, and if not stock display no stock in popup.










    share|improve this question







    New contributor




    DEEPAK KUMAR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.























      1












      1








      1







      I am just modifying magento add to cart ajax functionality.
      I want to check remain quantity of product if some is added to cart.
      But i tried ,many ways but i did not success.
      Instead of message manager, i want to display message in popup.



      I tried



      <?php
      /**
      *
      * Copyright © Magento, Inc. All rights reserved.
      * See COPYING.txt for license details.
      */
      namespace DevCheckoutControllerCart;

      use MagentoCatalogApiProductRepositoryInterface;
      use MagentoCheckoutModelCart as CustomerCart;
      use MagentoFrameworkExceptionNoSuchEntityException;
      use MagentoCatalogInventoryApiStockRegistryInterface;

      /**
      * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
      */
      class Add extends MagentoCheckoutControllerCart
      {
      /**
      * @var ProductRepositoryInterface
      */
      protected $productRepository;


      /**
      * @param MagentoFrameworkAppActionContext $context
      * @param MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
      * @param MagentoCheckoutModelSession $checkoutSession
      * @param MagentoStoreModelStoreManagerInterface $storeManager
      * @param MagentoFrameworkDataFormFormKeyValidator $formKeyValidator
      * @param CustomerCart $cart
      * @param ProductRepositoryInterface $productRepository
      * @codeCoverageIgnore
      */
      public function __construct(
      MagentoFrameworkAppActionContext $context,
      MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig,
      MagentoCheckoutModelSession $checkoutSession,
      MagentoStoreModelStoreManagerInterface $storeManager,
      MagentoFrameworkDataFormFormKeyValidator $formKeyValidator,
      MagentoCatalogInventoryApiStockStateInterface $StockStateInterface,
      CustomerCart $cart,
      ProductRepositoryInterface $productRepository,
      StockRegistryInterface $StockRegistryInterface
      ) {
      parent::__construct(
      $context,
      $scopeConfig,
      $checkoutSession,
      $storeManager,
      $formKeyValidator,
      $cart
      );
      $this->productRepository = $productRepository;
      $this->storeManager = $storeManager;
      $this->stockRegistryInterface = $StockRegistryInterface;
      }

      /**
      * Initialize product instance from request data
      *
      * @return MagentoCatalogModelProduct|false
      */
      protected function _initProduct()
      {
      $productId = (int)$this->getRequest()->getParam('product');
      if ($productId) {
      $storeId = $this->_objectManager->get(
      MagentoStoreModelStoreManagerInterface::class
      )->getStore()->getId();
      try {
      return $this->productRepository->getById($productId, false, $storeId);
      } catch (NoSuchEntityException $e) {
      return false;
      }
      }
      return false;
      }

      /**
      * Add product to shopping cart action
      *
      * @return MagentoFrameworkControllerResultRedirect
      * @SuppressWarnings(PHPMD.CyclomaticComplexity)
      */
      public function execute()
      {
      if (!$this->_formKeyValidator->validate($this->getRequest())) {
      return $this->resultRedirectFactory->create()->setPath('*/*/');
      }
      $params = $this->getRequest()->getParams();
      // Checking product quantity
      $productStockObj = $this->stockRegistryInterface->getStockItem($params['product']);
      $remainQty = $productStockObj->getQty();

      $requestFrom = '';
      if (array_key_exists('message-popup', $params)) {

      try {
      if (isset($params['qty'])) {
      $filter = new Zend_Filter_LocalizedToNormalized(
      ['locale' => $this->_objectManager->get(
      MagentoFrameworkLocaleResolverInterface::class
      )->getLocale()]
      );
      $params['qty'] = $filter->filter($params['qty']);
      }

      $product = $this->_initProduct();
      $related = $this->getRequest()->getParam('related_product');

      /**
      * Check product availability
      */
      if (!$product) {
      return $this->goBack();
      }


      $this->cart->addProduct($product, $params);
      if (!empty($related)) {
      $this->cart->addProductsByIds(explode(',', $related));
      }

      $this->cart->save();

      /**
      * @todo remove wishlist observer MagentoWishlistObserverAddToCart
      */
      $this->_eventManager->dispatch(
      'checkout_cart_add_product_complete',
      ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()]
      );

      if (!$this->_checkoutSession->getNoCartRedirect(true)) {
      if (!$this->cart->getQuote()->getHasError()) {
      if ($this->shouldRedirectToCart()) {
      $message = __(
      'You added %1 to your shopping cart.',
      $product->getName()
      );
      $this->messageManager->addSuccessMessage($message);
      } else {
      $this->messageManager->addComplexSuccessMessage(
      'addCartSuccessMessage',
      [
      'product_name' => $product->getName(),
      'cart_url' => $this->getCartUrl(),
      ]
      );
      }
      }
      return $this->goBack(null, $product);
      }
      } catch (MagentoFrameworkExceptionLocalizedException $e) {
      if ($this->_checkoutSession->getUseNotice(true)) {
      $this->messageManager->addNotice(
      $this->_objectManager->get(MagentoFrameworkEscaper::class)->escapeHtml($e->getMessage())
      );
      } else {
      $messages = array_unique(explode("n", $e->getMessage()));
      foreach ($messages as $message) {
      $this->messageManager->addError(
      $this->_objectManager->get(MagentoFrameworkEscaper::class)->escapeHtml($message)
      );
      }
      }

      $url = $this->_checkoutSession->getRedirectUrl(true);

      if (!$url) {
      $url = $this->_redirect->getRedirectUrl($this->getCartUrl());
      }

      return $this->goBack($url);
      } catch (Exception $e) {
      $this->messageManager->addException($e, __('We can't add this item to your shopping cart right now.'));
      $this->_objectManager->get(PsrLogLoggerInterface::class)->critical($e);
      return $this->goBack();
      }
      }
      }

      /**
      * Resolve response
      *
      * @param string $backUrl
      * @param MagentoCatalogModelProduct $product
      * @return $this|MagentoFrameworkControllerResultRedirect
      */
      protected function goBack($backUrl = null, $product = null)
      {
      if (!$this->getRequest()->isAjax()) {
      return parent::_goBack($backUrl);
      }

      $result = ;

      if ($backUrl || $backUrl = $this->getBackUrl()) {
      $result['backUrl'] = $backUrl;
      } else {
      if ($product && !$product->getIsSalable()) {
      $result['product'] = [
      'statusText' => __('Out of stock')
      ];
      }
      }

      $this->getResponse()->representJson(
      $this->_objectManager->get(MagentoFrameworkJsonHelperData::class)->jsonEncode($result)
      );
      }

      /**
      * @return string
      */
      private function getCartUrl()
      {
      return $this->_url->getUrl('checkout/cart', ['_secure' => true]);
      }

      /**
      * @return bool
      */
      private function shouldRedirectToCart()
      {
      return $this->_scopeConfig->isSetFlag(
      'checkout/cart/redirect_to_cart',
      MagentoStoreModelScopeInterface::SCOPE_STORE
      );
      }
      }


      I used
      MagentoCatalogInventoryApiStockRegistryInterface;
      function getStockItem();



      But i m not getting the remain stock of product.
      I need to validate product stock before add to cart, and if not stock display no stock in popup.










      share|improve this question







      New contributor




      DEEPAK KUMAR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      I am just modifying magento add to cart ajax functionality.
      I want to check remain quantity of product if some is added to cart.
      But i tried ,many ways but i did not success.
      Instead of message manager, i want to display message in popup.



      I tried



      <?php
      /**
      *
      * Copyright © Magento, Inc. All rights reserved.
      * See COPYING.txt for license details.
      */
      namespace DevCheckoutControllerCart;

      use MagentoCatalogApiProductRepositoryInterface;
      use MagentoCheckoutModelCart as CustomerCart;
      use MagentoFrameworkExceptionNoSuchEntityException;
      use MagentoCatalogInventoryApiStockRegistryInterface;

      /**
      * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
      */
      class Add extends MagentoCheckoutControllerCart
      {
      /**
      * @var ProductRepositoryInterface
      */
      protected $productRepository;


      /**
      * @param MagentoFrameworkAppActionContext $context
      * @param MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
      * @param MagentoCheckoutModelSession $checkoutSession
      * @param MagentoStoreModelStoreManagerInterface $storeManager
      * @param MagentoFrameworkDataFormFormKeyValidator $formKeyValidator
      * @param CustomerCart $cart
      * @param ProductRepositoryInterface $productRepository
      * @codeCoverageIgnore
      */
      public function __construct(
      MagentoFrameworkAppActionContext $context,
      MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig,
      MagentoCheckoutModelSession $checkoutSession,
      MagentoStoreModelStoreManagerInterface $storeManager,
      MagentoFrameworkDataFormFormKeyValidator $formKeyValidator,
      MagentoCatalogInventoryApiStockStateInterface $StockStateInterface,
      CustomerCart $cart,
      ProductRepositoryInterface $productRepository,
      StockRegistryInterface $StockRegistryInterface
      ) {
      parent::__construct(
      $context,
      $scopeConfig,
      $checkoutSession,
      $storeManager,
      $formKeyValidator,
      $cart
      );
      $this->productRepository = $productRepository;
      $this->storeManager = $storeManager;
      $this->stockRegistryInterface = $StockRegistryInterface;
      }

      /**
      * Initialize product instance from request data
      *
      * @return MagentoCatalogModelProduct|false
      */
      protected function _initProduct()
      {
      $productId = (int)$this->getRequest()->getParam('product');
      if ($productId) {
      $storeId = $this->_objectManager->get(
      MagentoStoreModelStoreManagerInterface::class
      )->getStore()->getId();
      try {
      return $this->productRepository->getById($productId, false, $storeId);
      } catch (NoSuchEntityException $e) {
      return false;
      }
      }
      return false;
      }

      /**
      * Add product to shopping cart action
      *
      * @return MagentoFrameworkControllerResultRedirect
      * @SuppressWarnings(PHPMD.CyclomaticComplexity)
      */
      public function execute()
      {
      if (!$this->_formKeyValidator->validate($this->getRequest())) {
      return $this->resultRedirectFactory->create()->setPath('*/*/');
      }
      $params = $this->getRequest()->getParams();
      // Checking product quantity
      $productStockObj = $this->stockRegistryInterface->getStockItem($params['product']);
      $remainQty = $productStockObj->getQty();

      $requestFrom = '';
      if (array_key_exists('message-popup', $params)) {

      try {
      if (isset($params['qty'])) {
      $filter = new Zend_Filter_LocalizedToNormalized(
      ['locale' => $this->_objectManager->get(
      MagentoFrameworkLocaleResolverInterface::class
      )->getLocale()]
      );
      $params['qty'] = $filter->filter($params['qty']);
      }

      $product = $this->_initProduct();
      $related = $this->getRequest()->getParam('related_product');

      /**
      * Check product availability
      */
      if (!$product) {
      return $this->goBack();
      }


      $this->cart->addProduct($product, $params);
      if (!empty($related)) {
      $this->cart->addProductsByIds(explode(',', $related));
      }

      $this->cart->save();

      /**
      * @todo remove wishlist observer MagentoWishlistObserverAddToCart
      */
      $this->_eventManager->dispatch(
      'checkout_cart_add_product_complete',
      ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()]
      );

      if (!$this->_checkoutSession->getNoCartRedirect(true)) {
      if (!$this->cart->getQuote()->getHasError()) {
      if ($this->shouldRedirectToCart()) {
      $message = __(
      'You added %1 to your shopping cart.',
      $product->getName()
      );
      $this->messageManager->addSuccessMessage($message);
      } else {
      $this->messageManager->addComplexSuccessMessage(
      'addCartSuccessMessage',
      [
      'product_name' => $product->getName(),
      'cart_url' => $this->getCartUrl(),
      ]
      );
      }
      }
      return $this->goBack(null, $product);
      }
      } catch (MagentoFrameworkExceptionLocalizedException $e) {
      if ($this->_checkoutSession->getUseNotice(true)) {
      $this->messageManager->addNotice(
      $this->_objectManager->get(MagentoFrameworkEscaper::class)->escapeHtml($e->getMessage())
      );
      } else {
      $messages = array_unique(explode("n", $e->getMessage()));
      foreach ($messages as $message) {
      $this->messageManager->addError(
      $this->_objectManager->get(MagentoFrameworkEscaper::class)->escapeHtml($message)
      );
      }
      }

      $url = $this->_checkoutSession->getRedirectUrl(true);

      if (!$url) {
      $url = $this->_redirect->getRedirectUrl($this->getCartUrl());
      }

      return $this->goBack($url);
      } catch (Exception $e) {
      $this->messageManager->addException($e, __('We can't add this item to your shopping cart right now.'));
      $this->_objectManager->get(PsrLogLoggerInterface::class)->critical($e);
      return $this->goBack();
      }
      }
      }

      /**
      * Resolve response
      *
      * @param string $backUrl
      * @param MagentoCatalogModelProduct $product
      * @return $this|MagentoFrameworkControllerResultRedirect
      */
      protected function goBack($backUrl = null, $product = null)
      {
      if (!$this->getRequest()->isAjax()) {
      return parent::_goBack($backUrl);
      }

      $result = ;

      if ($backUrl || $backUrl = $this->getBackUrl()) {
      $result['backUrl'] = $backUrl;
      } else {
      if ($product && !$product->getIsSalable()) {
      $result['product'] = [
      'statusText' => __('Out of stock')
      ];
      }
      }

      $this->getResponse()->representJson(
      $this->_objectManager->get(MagentoFrameworkJsonHelperData::class)->jsonEncode($result)
      );
      }

      /**
      * @return string
      */
      private function getCartUrl()
      {
      return $this->_url->getUrl('checkout/cart', ['_secure' => true]);
      }

      /**
      * @return bool
      */
      private function shouldRedirectToCart()
      {
      return $this->_scopeConfig->isSetFlag(
      'checkout/cart/redirect_to_cart',
      MagentoStoreModelScopeInterface::SCOPE_STORE
      );
      }
      }


      I used
      MagentoCatalogInventoryApiStockRegistryInterface;
      function getStockItem();



      But i m not getting the remain stock of product.
      I need to validate product stock before add to cart, and if not stock display no stock in popup.







      cart addtocart stock stock-status






      share|improve this question







      New contributor




      DEEPAK KUMAR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question







      New contributor




      DEEPAK KUMAR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question






      New contributor




      DEEPAK KUMAR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked yesterday









      DEEPAK KUMARDEEPAK KUMAR

      83




      83




      New contributor




      DEEPAK KUMAR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      DEEPAK KUMAR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      DEEPAK KUMAR is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          0






          active

          oldest

          votes











          Your Answer








          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "479"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });






          DEEPAK KUMAR is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f256890%2fhow-to-get-remain-stock-of-product-if-some-of-added-in-cart%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          DEEPAK KUMAR is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          DEEPAK KUMAR is a new contributor. Be nice, and check out our Code of Conduct.













          DEEPAK KUMAR is a new contributor. Be nice, and check out our Code of Conduct.












          DEEPAK KUMAR is a new contributor. Be nice, and check out our Code of Conduct.
















          Thanks for contributing an answer to Magento Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f256890%2fhow-to-get-remain-stock-of-product-if-some-of-added-in-cart%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          1300-talet

          1300-talet

          Display a custom attribute below product name in the front-end Magento 1.9.3.8