0

I tried to add the products to cart by using code. I tried with below code

class Producttocart extends \Magento\Framework\App\Action\Action {
 protected $formKey;
 protected $cart;
 protected $product;
 protected $pageFactory;
 public function __construct(
 \Magento\Framework\App\Action\Context $context, \Magento\Framework\Data\Form\FormKey $formKey, \Magento\Checkout\Model\Cart $cart, \Magento\Framework\View\Result\PageFactory $pageFactory, \Magento\Catalog\Model\Product $product, array $data = []
 ) {
 $this->formKey = $formKey;
 $this->cart = $cart;
 $this->product = $product;
 $this->pageFactory = $pageFactory;
 parent::__construct($context);
 }
 public function execute()
{
$minQty = 3;
 $cart_product = $this->getRequest()->getParams();
//echo "<pre>";print_r($cart_product);die("here");
foreach ($cart_product as $selecttid => $optionid) {
 if (strpos($selecttid, 'options') !== false) {
 $productoptions[$selecttid] = $optionid;
 }
 }
//echo "<pre>";print_r($productoptions);die("here");
 //$cart_product = $this->_productFactory->getCollection()->addAttributeToFilter('entity_id',array('product_id1','product_id2'));
 if ($cart_product) {
 foreach ($cart_product as $key => $value) {
 if($value > 0){
 $product = $this->_productFactory->create()->load($key);
 $customOptions = $this->_objectManager->create('Magento\Catalog\Model\Product\OptionFactory')->create()->getProductOptionCollection($product);
 $qty = $this->stockItem->getStockQty($product->getId(), $product->getStore()->getWebsiteId());

// echo $qty;die("here"); if ($value < $minQty) $value = $minQty; if ($value> $qty) { $this->messageManager->addError(__('The requested quantity for "%s" is not available.' . $product->getName())); }else{ if($customOptions){ $matches = array(); foreach ($productoptions as $selecttid => $optionid) { if (strpos($selecttid, $product->getId() . 'options') !== false && is_numeric($optionid) && stripos($selecttid, $product->getId() . 'options')==0) { $selecttid1 = str_replace($product->getId() . 'options', "", $selecttid); $matches[$selecttid1] = $optionid;

 }
 }
 //echo "<pre>";print_r($matches);die("here");
 $this->addCartProductwithOptions($product->getId(), $value, $matches);
 }else{
 $this->addCartProduct($key, $value);
 }
 }
 }
 }
 $this->_cart->save();
 }
 $this->_redirect("checkout/cart/add/form_key/");
}
public function addCartProduct($productID, $productQty)
{
 $product = $this->_productFactory->create()->load($productID);
 $info = new \Magento\Framework\DataObject(
 [
 'form_key' => $this->formKey->getFormKey(),
 'product_id' => $productID,
 'qty' => $productQty
 ]
 );
 return $this->_cart->addProduct($product, $info);
}
public function addCartProductwithOptions($productID, $productQty, $options)
{
//echo "<pre>";print_r($options);die("here");
 $product = $this->_productFactory->create()->load($productID);
 $info = new \Magento\Framework\DataObject(
 [
 'form_key' => $this->formKey->getFormKey(),
 'product_id' => $productID,
 'qty' => $productQty,
 'options' => $options
 ]
 );
 return $this->_cart->addProduct($product, $info);
}

In this $params value is array like

Array
(
 [form_key] => D6a4V5hbr9XO26zk
 [1] => 1 //here [productid] => qty
 [2] => 1 //here [productid] => qty
 [Add_to_Cart] => Add to Cart
)

Here $productoptions value is like this Array ( [1_options_3] => 3 [2_options_4] => None ) $matches value is like this Array ( [3] => 3 ) product is added to cart but its qty is double is after added to cart is double like below screnshot http://prntscr.com/lty4h9

when qty>0 and is_numeric($productId) product need to add to cart but above code is only one product is added to cart. how can i solve this issue?

asked Dec 12, 2018 at 7:16

2 Answers 2

0

You need to change your addProduct() function's param. Follow my below answer and add in your controller :

class Producttocart extends \Magento\Framework\App\Action\Action {
 protected $formKey;
 protected $_productFactory;
 protected $_cart;
 protected $messageManager;
 public function __construct(
 Context $context,
 \Magento\Framework\Data\Form\FormKey $formKey,
 \Magento\Framework\Message\ManagerInterface $managerInterface,
 \Magento\Catalog\Model\ProductFactory $productFactory,
 \Magento\Checkout\Model\Cart $cart
 ) {
 parent::__construct($context);
 $this->formKey = $formKey;
 $this->_productFactory = $productFactory;
 $this->_cart = $cart;
 $this->messageManager = $managerInterface;
 }
 public function execute()
 {
 //$cart_product = your product data collection or 
 //$cart_product = $this->_productFactory->getCollection()->addAttributeToFilter('entity_id',array('product_id1','product_id2'));
 if ($cart_product) {
 foreach ($cart_product as $key => $value) {
 if($value['qty'] > 0){
 $custom_option_value = '';
 if (isset($value['super_attribute']) || !empty($value['super_attribute'])) {
 $custom_option_value = $value['super_attribute'];
 }
 $this->addCartProduct($value['id'], $value['qty'],$custom_option_value);
 }
 }
 $this->_cart->save();
 }
 $this->_redirect("checkout/cart/add/form_key/");
 }
 public function addCartProduct($productID, $productQty,$custom_option_val)
 {
 $product = $this->_productFactory->create()->load($productID);
 $info = new \Magento\Framework\DataObject(
 [
 'form_key' => $this->formKey->getFormKey(),
 'product_id' => $productID,
 'qty' => $productQty,
 'super_attribute' => $custom_option_val
 ]
 );
 return $this->_cart->addProduct($product, $info);
 }
}
answered Dec 12, 2018 at 7:24
9
  • Thanks for u r reply, how can i add the custom options for this code? Commented Dec 12, 2018 at 9:51
  • please check my updated answer. Commented Dec 12, 2018 at 10:16
  • i think, u r wrote code for configurable product but i need the simple products custom options code Commented Dec 12, 2018 at 10:44
  • No. It's for simple product. Commented Dec 12, 2018 at 10:45
  • You can see here also : magento.stackexchange.com/a/244946/51810 Commented Dec 12, 2018 at 10:45
1
<?php
namespace Demo\Addtocart\Controller\Index;
use Magento\Framework\App\Action\Context;
class Customaddtocart extends \Magento\Framework\App\Action\Action
{
 protected $checkoutSession;
 protected $_productloader;
 protected $cartRepository;
 public function __construct(Context $context,
 \Magento\Catalog\Model\ProductFactory $_productloader,
 \Magento\Checkout\Model\Session $checkoutSession,
 \Magento\Quote\Api\CartRepositoryInterface $cartRepository,
 array $data = [])
 {
 $this->checkoutSession = $checkoutSession;
 $this->cartRepository = $cartRepository;
 $this->_productloader = $_productloader;
 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();
 }
}
answered Dec 12, 2018 at 7:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.