3

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

code is:

Here am passing custom parameters to cart: lqty, lproduct

    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 test(){
    $params = $this->getRequest()->getParams();
    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();

        //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();
    }

}


/**
 * Add product to shopping cart action
 *
 * @return \Magento\Framework\Controller\Result\Redirect
 * @SuppressWarnings(PHPMD.CyclomaticComplexity)
 */

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);
    */

    if($this->getRequest()->getParam('lqty')){

        $this->newProduct();
        $this->test();

    }else{

        $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();

            //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();
        }
    }
}

/**
 * Resolve response
 *
 * @param string $backUrl
 * @param \Magento\Catalog\Model\Product $product
 * @return $this|\Magento\Framework\Controller\Result\Redirect
 */
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('Magento\Framework\Json\Helper\Data')->jsonEncode($result)
    );
}
1
  • Can any one please provide the solution. – Ramesh Jun 22 '17 at 10:46
0

For adding multiple products to cart at one time , you have to send product id in array . please see below code

in yourvendor/module/view/products/list.phtml use Magento\Framework\App\Action\Action;

            $_productCollection = $block->getLoadedProductCollection();

            $_helper = $this->helper('Magento\Catalog\Helper\Output');

            $ys_helper = $this->helper('Etheme\Yourstore\Helper\Data');

            /*$products_size = $ys_helper->getSystemValue('yourstore_settings/product_listing/products_size_row');*/

            $sale_label = $ys_helper->getSystemValue('yourstore_settings/product_listing/sale_label');

            $new_label = $ys_helper->getSystemValue('yourstore_settings/product_listing/new_label');

            $specials_counter = $ys_helper->getSystemValue('yourstore_settings/product_listing/specials_counter');

            $products_size = 1;


            if ($products_size == 0) { $classes_set = ' col-xs-6 col-sm-4 col-md-6 col-lg-4 col-xl-one-fifth'; }

            if ($products_size == 1) { $classes_set = ' col-xs-6 col-sm-4 col-md-3 col-lg-2 col-xl-one-nine'; }

            if ($products_size == 2) { $classes_set = ' col-xs-6 col-sm-4 col-md-4 col-lg-3 col-xl-2'; }

            if ($products_size == 3) { $classes_set = ' col-xs-12 col-sm-6 col-md-6 col-lg-6 col-xl-4'; }

            ?>

            <?php if (!$_productCollection->count()): ?>

                <div class="text-center">

                    <img src="<?php echo $block->getViewFileUrl('images'); ?>/empty-category-icon.png" alt="empty category icon" class="img-responsive-inline">

                    <div class="divider divider--lg"></div>

                    <h4 class="color"><?php /* @escapeNotVerified */ echo __('We can\'t find products matching the selection.') ?></h4>

                </div>

            <?php else: ?>

                <?php echo $block->getToolbarHtml() ?>

                <?php echo $block->getAdditionalHtml() ?>

                <?php

                if ($block->getMode() == 'grid') {

                    $viewMode = 'grid';

                    $image = 'category_page_grid';

                    $showDescription = false;

                    $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::SHORT_VIEW;

                } else {

                    $viewMode = 'list';

                    $image = 'category_page_list';

                    $showDescription = true;

                    $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::FULL_VIEW;

                }

                /**

                 * Position for actions regarding image size changing in vde if needed

                 */

                $pos = $block->getPositioned();

                ?>
                    <form class="listing_form" data-role="tocart-form" action="<?php echo $block->getUrl('checkout/cart/add')?>" method="post">
                <div class="products wrapper <?php /* @escapeNotVerified */ echo $viewMode; ?> products-<?php /* @escapeNotVerified */ echo $viewMode; ?>">

                    <?php $iterator = 1; ?>



                    <ol class="products list items product-items custom-height-count row">

                        <?php /** @var $_product \Magento\Catalog\Model\Product */ ?>

                        <?php foreach ($_productCollection as $fkey=>$_product): ?>



                            <?php echo($iterator++ == 1) ? '<li class="item product-item'.$classes_set.'">' : '</li><li class="item product-item'.$classes_set.'">' ?>

                            <div class="item_placeholder"></div>

                            <div class="product-item-info product_holder" data-container="product-grid">

                            <div class="product_holder__inside">

                                <?php

                                $productImage = $block->getImage($_product, $image);

                                if ($pos != null) {

                                    $position = ' style="left:' . $productImage->getWidth() . 'px;'

                                        . 'top:' . $productImage->getHeight() . 'px;'.'height:300px;"';

                                }

                                ?>

                                <?php // Product Image ?>

                                <div class="product photo product-item-photo">

                                    <?php if ($specials_counter): ?>

                                    <?php echo $this->helper('Etheme\Yourstore\Helper\Data')->getCountdown($_product); ?>

                                    <?php endif; ?>

                                    <?php if ($sale_label): ?>

                                    <?php echo $this->helper('Etheme\Yourstore\Helper\Data')->saleLabel($_product); ?>

                                    <?php endif; ?>

                                    <?php if ($new_label): ?>

                                    <?php echo $this->helper('Etheme\Yourstore\Helper\Data')->newLabel($_product); ?>

                                    <?php endif; ?>



                                   <!--  <a href="<?php echo $_product->getProductUrl() ?>" tabindex="-1"> -->
                                        <input type="checkbox" id="chk<?=$fkey?>" value="<?=$_product->getId();?>" name="productIds[]"/>
                                        <label for="chk<?=$fkey?>" class="labels">
                                       <?php echo $productImage->toHtml();?>
                                        </label>                             


                                    <!-- </a> -->

                                    <?php

                                    $buttonStyle = 'weltpixel_quickview_button_' . $ys_helper->getSystemValue('weltpixel_quickview/general/button_style');

                                    $productUrl = $this->getUrl('weltpixel_quickview/catalog_product/view', array('id' => $_product->getId()));

                                    echo '<a class="weltpixel-quickview quick-view '.$buttonStyle.'" data-quickview-url=' . $productUrl . ' href="javascript:void(0);"><b><span class="icon icon-visibility"></span>' . __("Quick view") . '</b></a>';

                                    ?>

                                </div>

                                <div class="product details product-item-details">

                                    <?php

                                        $_productNameStripped = $block->stripTags($_product->getName(), null, true);

                                    ?>

                                    <div class="product name product-item-name">

                                        <h2>

                                            <a class="product-item-link"

                                               href="<?php /* @escapeNotVerified */ echo $_product->getProductUrl() ?>">

                                                <?php /* @escapeNotVerified */ echo $_helper->productAttribute($_product, $_product->getName(), 'name'); ?>

                                            </a>

                                        </h2>

                                    </div>



                                    <?php if ($showDescription):?>

                                        <div class="product description product-item-description row-mode-visible">

                                            <?php /* @escapeNotVerified */ echo $_helper->productAttribute($_product, $_product->getShortDescription(), 'short_description') ?>

                                            <a href="<?php /* @escapeNotVerified */ echo $_product->getProductUrl() ?>" title="<?php /* @escapeNotVerified */ echo $_productNameStripped ?>"

                                               class="action more"><?php /* @escapeNotVerified */ echo __('Learn More') ?></a>

                                        </div>

                                    <?php endif; ?>



                                    <?php /* @escapeNotVerified */ echo $block->getProductPrice($_product) ?>



                                    <div class="product_holder__inside__review row-mode-visible">

                                        <div class="rating row-mode-visible">

                                            <?php echo $block->getReviewsSummaryHtml($_product, $templateType); ?>

                                        </div>

                                    </div>



                                    <div class="product-item-inner product_holder__inside__hover">

                                        <div class="product actions product-item-actions product_holder__inside__info"<?php echo strpos($pos, $viewMode . '-actions') ? $position : ''; ?>>

                                            <?php echo $block->getProductDetailsHtml($_product); ?>

                                            <div class="product_holder__inside__info__btns">

                                                <div class="actions-primary"<?php echo strpos($pos, $viewMode . '-primary') ? $position : ''; ?>>

                                                    <?php if ($_product->isSaleable()): ?>

                                                        <?php $postParams = $block->getAddToCartPostParams($_product); ?>


                                                            <?php echo $block->getBlockHtml('formkey')?>


                                                    <?php else: ?>

                                                        <?php if ($_product->getIsSalable()): ?>

                                                            <div class="stock available"><span><?php /* @escapeNotVerified */ echo __('In stock') ?></span></div>

                                                        <?php else: ?>

                                                            <div class="stock unavailable"><span><?php /* @escapeNotVerified */ echo __('Out of stock') ?></span></div>

                                                        <?php endif; ?>

                                                    <?php endif; ?>



                                                    <?php

                                                    $buttonStyle = 'weltpixel_quickview_button_' . $ys_helper->getSystemValue('weltpixel_quickview/general/button_style');

                                                    $productUrl = $this->getUrl('weltpixel_quickview/catalog_product/view', array('id' => $_product->getId()));

                                                    echo '<a class="btn btn--ys btn--xl row-mode-visible weltpixel-quickview '.$buttonStyle.'" data-quickview-url=' . $productUrl . ' href="javascript:void(0);"><b><span class="icon icon-visibility"></span>' . __("Quick view") . '</b></a>';

                                                    ?>



                                                    <?php if ($this->helper('Magento\Wishlist\Helper\Data')->isAllow()): ?>

                                                        <a href="#"

                                                           class="btn btn--ys btn--xl visible-xs"

                                                           title="<?php echo $block->escapeHtml(__('Add to Wish List')); ?>"

                                                           aria-label="<?php echo $block->escapeHtml(__('Add to Wish List')); ?>"

                                                           data-post='<?php /* @escapeNotVerified */ echo $block->getAddToWishlistParams($_product); ?>'

                                                           data-action="add-to-wishlist"

                                                           role="button">

                                                            <span class="icon icon-favorite_border"></span>

                                                        </a>

                                                    <?php endif; ?>

                                                    <?php

                                                    $compareHelper = $this->helper('Magento\Catalog\Helper\Product\Compare');

                                                    ?>

                                                    <a href="#"

                                                       class="btn btn--ys btn--xl visible-xs"

                                                       title="<?php echo $block->escapeHtml(__('Add to Compare')); ?>"

                                                       aria-label="<?php echo $block->escapeHtml(__('Add to Compare')); ?>"

                                                       data-post='<?php /* @escapeNotVerified */ echo $compareHelper->getPostDataParams($_product); ?>'

                                                       role="button">

                                                        <span class="icon icon-sort"></span>

                                                    </a>

                                                </div>

                                            </div>



                                            <div data-role="add-to-links" class="actions-secondary product_holder__inside__info__link hidden-sm"<?php echo strpos($pos, $viewMode . '-secondary') ? $position : ''; ?>>

                                                <?php if ($this->helper('Magento\Wishlist\Helper\Data')->isAllow()): ?>

                                                    <a href="#"

                                                       class="action towishlist"

                                                       title="<?php echo $block->escapeHtml(__('Add to Wish List')); ?>"

                                                       aria-label="<?php echo $block->escapeHtml(__('Add to Wish List')); ?>"

                                                       data-post='<?php /* @escapeNotVerified */ echo $block->getAddToWishlistParams($_product); ?>'

                                                       data-action="add-to-wishlist"

                                                       role="button">

                                                        <span><?php /* @escapeNotVerified */ echo __('Add to Wish List') ?></span>

                                                    </a>

                                                <?php endif; ?>

                                                <?php

                                                $compareHelper = $this->helper('Magento\Catalog\Helper\Product\Compare');

                                                ?>

                                                <a href="#"

                                                   class="action tocompare"

                                                   title="<?php echo $block->escapeHtml(__('Add to Compare')); ?>"

                                                   aria-label="<?php echo $block->escapeHtml(__('Add to Compare')); ?>"

                                                   data-post='<?php /* @escapeNotVerified */ echo $compareHelper->getPostDataParams($_product); ?>'

                                                   role="button">

                                                    <span><?php /* @escapeNotVerified */ echo __('Add to Compare') ?></span>

                                                </a>

                                            </div>

                                        </div>



                                        <div class="rating row-mode-hide">

                                            <?php echo $block->getReviewsSummaryHtml($_product, $templateType); ?>

                                        </div>



                                    </div>



                                </div>

                            </div>

                            </div>

                            <?php echo($iterator == count($_productCollection)+1) ? '</li>' : '' ?>

                        <?php endforeach; ?>

                    </ol>
                </div>
               <?php echo $block->getToolbarHtml() ?>

                   <button type="submit"
                            title="<?php echo $block->escapeHtml(__('Add to Cart')); ?>"
                            class="action tocart primary btn--ys btn--xl">
                            <i class="icon icon-shopping_basket"></i>
                            <span><?php /* @escapeNotVerified */ echo __('Add Selected Items to Cart') ?></span>
                    </button>

                </form>                   


                <?php if (!$block->isRedirectToCartEnabled()) : ?>

                    <script type="text/x-magento-init">

                    {

                        "[data-role=tocart-form], .form.map.checkout": {

                            "catalogAddToCart": {}

                        }

                    }

                    </script>
                <?php endif; ?>

            <?php endif; ?>

and in magento/checkout/cart/add controller file include the below code

<?php
/**
 *
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Checkout\Controller\Cart;

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Checkout\Model\Cart as CustomerCart;
use Magento\Framework\Exception\NoSuchEntityException;

/**
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class Add extends \Magento\Checkout\Controller\Cart
{
/**
 * @var ProductRepositoryInterface
 */
protected $productRepository;

/**
 * @param \Magento\Framework\App\Action\Context $context
 * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
 * @param \Magento\Checkout\Model\Session $checkoutSession
 * @param \Magento\Store\Model\StoreManagerInterface $storeManager
 * @param \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator
 * @param CustomerCart $cart
 * @param ProductRepositoryInterface $productRepository
 * @codeCoverageIgnore
 */
public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
    \Magento\Checkout\Model\Session $checkoutSession,
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator,
    CustomerCart $cart,
    ProductRepositoryInterface $productRepository
) {
    parent::__construct(
        $context,
        $scopeConfig,
        $checkoutSession,
        $storeManager,
        $formKeyValidator,
        $cart
    );
    $this->productRepository = $productRepository;
}

/**
 * Initialize product instance from request data
 *
 * @return \Magento\Catalog\Model\Product|false
 */
protected function _initProduct($pid='')
{
    if($pid){
       $productId = $pid;  
    }else{
        $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;
}

/**
 * Add product to shopping cart action
 *
 * @return \Magento\Framework\Controller\Result\Redirect
 * @SuppressWarnings(PHPMD.CyclomaticComplexity)
 */
public function execute()
{
    if (!$this->_formKeyValidator->validate($this->getRequest())) {
        return $this->resultRedirectFactory->create()->setPath('*/*/');
    }

    $params = $this->getRequest()->getParams();
    $pId = $this->getRequest()->getParam('productIds');//productId
    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']);
        }

        /*Multiple product add to cart at one click - Modified Coding*/
        if(!empty($pId)){
            foreach ($pId as $productid):
                $productid = (int)$productid;
                $product = $this->_initProduct($productid);
                /**
                 * Check product availability
                 */
                if (!$product) {
                    return $this->goBack();
                }
                $this->cart->addProduct($product, $params);
                if (!$this->cart->getQuote()->getHasError()) {
                    $message = __(
                        'You added %1 to your shopping cart.',
                        $product->getName()
                    );
                    $this->messageManager->addSuccessMessage($message);
                }
            endforeach;
        }else{
            /*Original Coding for add product to cart */
          $product = $this->_initProduct();  
            /**
                 * Check product availability
                 */
                if (!$product) {
                    return $this->goBack();
                }
                $this->cart->addProduct($product, $params);
                if (!$this->cart->getQuote()->getHasError()) {
                    $message = __(
                        'You added %1 to your shopping cart.',
                        $product->getName()
                    );
                    $this->messageManager->addSuccessMessage($message);
                }
        }


        $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 \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)) {               
            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 now.'));
        $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
        return $this->goBack();
    }
}

/**
 * Resolve response
 *
 * @param string $backUrl
 * @param \Magento\Catalog\Model\Product $product
 * @return $this|\Magento\Framework\Controller\Result\Redirect
 */
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('Magento\Framework\Json\Helper\Data')->jsonEncode($result)
    );
}
}

it works fine for me

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.