0

In list page I have created the only two add to cart buttons instead of every product and created the Qty textbox for every product. When customer entered the Qty hit the Add to Cart button I am adding the products to cart. So for this I am trying to add products to cart in my custom module and it's added to cart but not showing in my cart. When ever I refreshed the page showing messages this product added to cart like this. And one more thing is after added products it's not refreshed the page automatically.

For this I have written below code.

root/app/code/Test/CustomCart/view/frontend/templates/product/list.phtml

 <form data-role="tocart-form" action="<?php /* @escapeNotVerified */ echo $block->getBaseUrl() . 'addtocart/index/index'; ?>" method="post">
            <div style="text-align: center;">
                    <button type="submit"
                            title="<?php echo $block->escapeHtml(__('Add to Cart')); ?>"
                            class="action tocart primary">
                        <span><?php /* @escapeNotVerified */ echo __('Add to Cart') ?></span>
                    </button>
            </div>
            <!--End the Custom Button-->
            <?php /** @var $_product \Magento\Catalog\Model\Product */ ?>
            <?php foreach ($_productCollection as $_product): ?>
................
core code
.....................
</form>

root/app/code/Test/CustomCart/Controller/Index/Index.php

<?php

namespace Test\CustomCart\Controller\Index;

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

class Index extends \Magento\Framework\App\Action\Action
{

    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * @var \Magento\Catalog\Model\ProductFactory
     */
    protected $_productFactory;


    /**
     * @var ProductRepositoryInterface
     */
    protected $productRepository;


    /**
     * @var \Magento\Checkout\Model\Cart
     */
    protected $cart;

    /**
     * @var \Magento\Checkout\Model\Session
     */
    protected $_checkoutSession;


    protected $_urlInterface;


    public function __construct(\Magento\Framework\App\Action\Context $context,\Magento\Framework\View\Result\PageFactory $pageFactory,\Magento\Catalog\Model\ProductFactory $productFactory,ProductRepositoryInterface $productRepository,\Magento\Checkout\Model\Session $checkoutSession,CustomerCart $cart,\Magento\Checkout\Model\Session $checkoutSession,\Magento\Framework\UrlInterface $urlInterface)
    {
        $this->resultPageFactory = $pageFactory;
        $this->productRepository = $productRepository;
        $this->_productFactory = $productFactory;
        $this->cart = $cart;
        $this->_checkoutSession = $checkoutSession;
        $this->_urlInterface = $urlInterface;
        parent::__construct($context);
    }

    /**
     *
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|void
     */
    public function execute()
    {

        $resultRedirect = $this->resultRedirectFactory->create();
        $resultRedirect->setUrl($this->_urlInterface->getBaseUrl());

        try{


            $resultPage = $this->resultPageFactory->create();
            $request = $this->getRequest()->getParams();
            $sku_list = [];

            foreach($request as $k => $v){
                if (strpos($k, 'qty_') !== false) {
                    $sku = explode('_',$k);
                    if($v !="" || $v !=0)
                        $sku_list[$sku[1]] = $v;
                }
            }

            $product = $this->_productFactory->create();

            foreach($sku_list as $k => $v){
                $data = $product->loadByAttribute('sku',$k);
                $product = $this->_initProduct($data->getId());

                /**
                 * Check product availability
                 */
                if (!$product) {
                    return $resultRedirect;
                }

                $params = array('product' => $product->getId(),'qty' => $v);
                $_product = $this->productRepository->getById($product->getId());
                $this->cart->addProduct($_product,$params);
                $this->cart->save();

                $message = __('You added %1 to your shopping cart.',$product->getName());
                $this->messageManager->addSuccessMessage($message);

            }

            return $resultRedirect;

        }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 $resultRedirect;

        } 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 $resultRedirect;
        }


    }


    protected function _initProduct($productId)
    {
        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;
    }


}

enter image description here

could you please guide me how can do this?

0

Finally, I solved this by removing the $this->cart->save(); from foreach and pasted the outside of foreach loop.

/**
     *
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|void
     */
    public function execute()
    {

        $resultRedirect = $this->resultRedirectFactory->create();
        $resultRedirect->setUrl($this->_urlInterface->getBaseUrl());

        try{


            $resultPage = $this->resultPageFactory->create();
            $request = $this->getRequest()->getParams();
            $sku_list = [];

            foreach($request as $k => $v){
                if (strpos($k, 'qty_') !== false) {
                    $sku = explode('_',$k);
                    if($v !="" || $v !=0)
                        $sku_list[$sku[1]] = $v;
                }
            }

            $product = $this->_productFactory->create();

            foreach($sku_list as $k => $v){
                $data = $product->loadByAttribute('sku',$k);
                $product = $this->_initProduct($data->getId());

                /**
                 * Check product availability
                 */
                if (!$product) {
                    return $resultRedirect;
                }

                $params = array('product' => $product->getId(),'qty' => $v);
                $_product = $this->productRepository->getById($product->getId());
                $this->cart->addProduct($_product,$params);


                $message = __('You added %1 to your shopping cart.',$product->getName());
                $this->messageManager->addSuccessMessage($message);

            }
            $this->cart->save();
            return $resultRedirect;

        }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 $resultRedirect;

        } 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 $resultRedirect;
        }


    }

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.