0

I am trying to add multiple products to Cart at one time, But i am facing issue while second product adding to cart as per attached screen shot. The second product showing in cart items but price is not displaying properly, it always shows as "0" and not updated in items count.

enter image description here

 protected function _initProduct() {
     $productId = (int)$this->getRequest()->getParam('product');
      if ($productId) {
          $storeId = $this->_objectManager-> 
        get('Magento\Store\Model\StoreManagerInterface')->getStore()->getId();
    try {
        return $this->productRepository->getById($productId, false, $storeId);
    } catch (NoSuchEntityException $e) {
        return false;
    }
  }
 return false;
 }

protected function _initinnerproduct()
{
$productId = (int)$this->getRequest()->getParam('lproduct');
if ($productId) {
    $storeId = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface')->getStore()->getId();
    try {
        return $this->productRepository->getById($productId, false, $storeId);
    } catch (NoSuchEntityException $e) {
        return false;
    }
  }
return false;
 }

 public function newProduct() {

if (!$this->_formKeyValidator->validate($this->getRequest())) {
    return $this->resultRedirectFactory->create()->setPath('*/*/');
}

$params = $this->getRequest()->getParams();

try {
    if (isset($params['lqty'])) {
        $filter = new \Zend_Filter_LocalizedToNormalized(
            ['locale' => $this->_objectManager->get('Magento\Framework\Locale\ResolverInterface')->getLocale()]
        );
        $params['qty'] = $filter->filter($params['lqty']);

        $paramsqty = new \Zend\Log\Writer\Stream(BP . '/var/log/qty1.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($paramsqty);
        $logger->info($params['qty']);
    }

    $product = $this->_initinnerproduct();

    $related = $this->getRequest()->getParam('lrelated_product');

    /**
     * Check product availability */

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

    $cartResut = $this->cart->save();

    $cart = new \Zend\Log\Writer\Stream(BP . '/var/log/cart-result.log');
    $logger = new \Zend\Log\Logger();
    $logger->addWriter($cart);
    $logger->info($cartResut);

    /**
     * @todo remove wishlist observer \Magento\Wishlist\Observer\AddToCart
     */
    $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()) {

            $message = __(
                'You added %1 to your shopping cart.',
                $product->getName()
            );
            $this->messageManager->addSuccessMessage($message);
        }
        return $this->goBack(null, $product);
    }
} catch (\Magento\Framework\Exception\LocalizedException $e) {
    if ($this->_checkoutSession->getUseNotice(true)) {
        $this->messageManager->addNotice(
            $this->_objectManager->get('Magento\Framework\Escaper')->escapeHtml($e->getMessage())
        );
    } else {
        $messages = array_unique(explode("\n", $e->getMessage()));
        foreach ($messages as $message) {
            $this->messageManager->addError(
                $this->_objectManager->get('Magento\Framework\Escaper')->escapeHtml($message)
            );
        }
    }

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

    if (!$url) {
        $cartUrl = $this->_objectManager->get('Magento\Checkout\Helper\Cart')->getCartUrl();
        $url = $this->_redirect->getRedirectUrl($cartUrl);
    }

    return $this->goBack($url);

} catch (\Exception $e) {
    $this->messageManager->addException($e, __('We can\'t add this item to your shopping cart right now321.'));
    $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
    return $this->goBack();
   }
 }

 public function execute(){
    if (!$this->_formKeyValidator->validate($this->getRequest())) {
       return $this->resultRedirectFactory->create()->setPath('*/*/');
    }
$params = $this->getRequest()->getParams();

/*
    $paramslogfirst = new \Zend\Log\Writer\Stream(BP . '/var/log/params123.log');
    $logger = new \Zend\Log\Logger();
    $logger->addWriter($paramslogfirst);
    $logger->info($params);
*/


    $else = new \Zend\Log\Writer\Stream(BP . '/var/log/else.log');
    $logger = new \Zend\Log\Logger();
    $logger->addWriter($else);
    $logger->info("Else Condition");

    try {
        if (isset($params['qty'])) {
            $filter = new \Zend_Filter_LocalizedToNormalized(
                ['locale' => $this->_objectManager->get('Magento\Framework\Locale\ResolverInterface')->getLocale()]
            );
            $params['qty'] = $filter->filter($params['qty']);

            $paramsqty = new \Zend\Log\Writer\Stream(BP . '/var/log/qty.log');
            $logger = new \Zend\Log\Logger();
            $logger->addWriter($paramsqty);
            $logger->info($params['qty']);
        }

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

        /**
         * Check product availability */

        if (!$product) {
            return $this->goBack();
        }

        //$this->newProduct();

        $this->cart->addProduct($product, $params);

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

        $this->newProduct();

        //exit;

        /**
         * @todo remove wishlist observer \Magento\Wishlist\Observer\AddToCart
         */
        $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()) {
                $message = __(
                    'You added %1 to your shopping cart.',
                    $product->getName()
                );
                $this->messageManager->addSuccessMessage($message);
            }
            return $this->goBack(null, $product);
        }
    } catch (\Magento\Framework\Exception\LocalizedException $e) {
        if ($this->_checkoutSession->getUseNotice(true)) {
            $this->messageManager->addNotice(
                $this->_objectManager->get('Magento\Framework\Escaper')->escapeHtml($e->getMessage())
            );
        } else {
            $messages = array_unique(explode("\n", $e->getMessage()));
            foreach ($messages as $message) {
                $this->messageManager->addError(
                    $this->_objectManager->get('Magento\Framework\Escaper')->escapeHtml($message)
                );
            }
        }

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

        if (!$url) {
            $cartUrl = $this->_objectManager->get('Magento\Checkout\Helper\Cart')->getCartUrl();
            $url = $this->_redirect->getRedirectUrl($cartUrl);
        }

        return $this->goBack($url);

    } catch (\Exception $e) {
        $this->messageManager->addException($e, __('We can\'t add this item to your shopping cart right now123.'));
        $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
        return $this->goBack();
     }

  }

1 Answer 1

0

in my case the problem was that I could not add more than 1 item to the cart.

Go To

vendor/magento/module-checkout/Controller/Cart/Add.php execute()

In filter($ params ['qty']) function of the Zend_Filter_LocalizedToNormalized class something was wrong.

Best regard,

Reference

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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