app/code/Ktpl/Addtocart/Controller/Index/Customaddtocart.php
<?php
namespace Ktpl\Addtocart\Controller\Index;
use Magento\Framework\App\Action\Context;
class Customaddtocart extends \Magento\Framework\App\Action\Action
{
protected $resultPageFactory;
protected $checkoutSession;
protected $_productloader;
protected $cartRepository;
protected $productRepository;
protected $_messageManager;
public function __construct(Context $context,
\Magento\Catalog\Model\ProductFactory $_productloader,
\Magento\Framework\View\Result\PageFactory $resultPageFactory,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Quote\Api\CartRepositoryInterface $cartRepository,
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
\Magento\Framework\Message\ManagerInterface $messageManager,
array $data = [])
{
$this->resultPageFactory = $resultPageFactory;
$this->checkoutSession = $checkoutSession;
$this->cartRepository = $cartRepository;
$this->productRepository = $productRepository;
$this->_productloader = $_productloader;
$this->_messageManager = $messageManager;
parent::__construct($context);
}
public function execute()
{
$post = $this->getRequest()->getPost();
$addtocartid = $post['addtocartid'];
$qty = $post['qty'];
$addtocartid=explode(",", $addtocartid);
$qty=explode(",", $qty);
$quote = $this->checkoutSession->getQuote();
for($j = 0; $j < count($addtocartid); $j++)
{
$_product = $this->_productloader->create()->load($addtocartid[$j]);
$quote->addProduct($_product, (int)$qty[$j]);
}
$this->cartRepository->save($quote);
$this->checkoutSession->replaceQuote($quote)->unsLastRealOrderId();
}
}
app/code/Ktpl/Addtocart/etc/frontend/sections.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
<action name="addtocart/index/customaddtocart">
<section name="cart"/>
</action>
</config>
\Magento\Checkout\Model\Cart
is deprecated, says to use\Magento\Quote\Model\Quote
instead, but doesn't appear to add the price to the item correctly.$this->response->setRedirect($this->getUrl('checkout'))->send();
after (which refreshes the page). If I manually refresh the page after it loads, the price appears. Is there a better way instead ofsetRedirect
which will ensure the totals are updated upon refresh?\Magento\Quote\Api\CartRepositoryInterface
. After adding successfully to cart, the last product showing zero totals. Thanks in Advance