3

I want to add a product with a bunch of options in the current cart via controller. How should I do this? And then what do I need to do if I want to remove it later on?

Joel
  • 175
  • 4
  • 15
  • I believe there are 2 approaches used currently. The old approach is used by the current checkout page which uses the controller to add items to the cart. At some point we'll be refactoring to use the interfaces in Quote to add items to the cart and passing those items an extensible object that specifies the custom options for that item. That's how we handled non-simple products in the cart APIs. You can look at the REST api documentation for info on specifying custom options for items ( http://devdocs.magento.com/swagger/index.html ; quoteCartItemRepository). – Chuck Jan 15 '16 at 22:56
  • I didn't know such a reference exists, million thanks – Joel Jan 16 '16 at 01:44
  • Also in a Magento 2 instance with custom services you can get your own API reference by hitting http://BASEURL/swagger . – Chuck Jan 19 '16 at 14:45

4 Answers4

3

In your customer controller :- Add product into cart

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

         /**
          * @var \Magento\Checkout\Model\Cart
          */
         protected $cart;
         /**
          * @var \Magento\Catalog\Model\Product
          */
         protected $product;
         /**
          * @var \Magento\Framework\Message\ManagerInterface
          */
         protected $messageManager;

         public function __construct(
             \Magento\Framework\App\Action\Context $context,
             \Magento\Framework\View\Result\PageFactory $resultPageFactory,
             \Magento\Catalog\Model\Product $product,
             \Magento\Checkout\Model\Cart $cart,
             \Magento\Framework\Message\ManagerInterface $messageManager
         ) {
             $this->resultPageFactory = $resultPageFactory;
             $this->_customerSession = $customerSession;
             $this->cart = $cart;
             $this->product = $product;
             $this->messageManager = $messageManager;
             parent::__construct($context);
         }
         public function execute()
         {
             try {
                 $params = array();
                 $params['qty'] = '1';//product quantity
                 /*get product id*/
                 $pId = '1';//productId
                 $_product = $this->product->load($pId);
                 if ($_product) {
                     $this->cart->addProduct($_product, $params);
                     $this->cart->save();
                 }

                 $this->messageManager->addSuccess(__('Add to cart successfully.'));
             } catch (\Magento\Framework\Exception\LocalizedException $e) {
                 $this->messageManager->addException(
                     $e,
                     __('%1', $e->getMessage())
                 );
             } catch (\Exception $e) {
                 $this->messageManager->addException($e, __('error.'));
             }
             /*cart page*/
             $this->getResponse()->setRedirect('/checkout/cart/index');


         }
    }

Remove product :-

1:- get item id from quote.

2:- remove code :-

   try {
            //$id => item id 
            $this->cart->removeItem($id)->save();
        } catch (\Exception $e) {
            $this->messageManager->addError(__('We can\'t remove the item.'));
            $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
        }
muhkuh2005
  • 29
  • 7
vikaskimt
  • 41
  • 3
  • This works but the mini cart top right does not update – Alex Mar 31 '16 at 12:31
  • 1
    I tried your code but its not working. I am trying to add product to cart using observer event checkout_cart_product_add_after but the code doesn't work. Could you please let me know where $this->_customerSession = $customerSession; is used? – Dexter May 18 '16 at 14:14
  • $this->messageManager is undefined – Kumar A. Mar 31 '17 at 14:49
0
   save the cart through sku
<?php
 namespace GreenPlank\Addtocart\Controller\Index;

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

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

protected $productRepository;

// protected $_productFactory;

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\View\Result\PageFactory $resultPageFactory,
    \Magento\Catalog\Model\Product $product,
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
    // \Magento\Catalog\Model\ProductFactory $_productFactory,
    \Magento\Checkout\Model\Cart $cart
) {
    $this->resultPageFactory = $resultPageFactory;
    $this->cart = $cart;
    $this->product = $product;
    $this->productRepository = $productRepository;
    // $this->productFactory = $_productFactory;
    parent::__construct($context);
}
public function execute()
{
    try {
        $params = array();
        $params['qty'] = '1';//product quantity
        /*get product id*/
        // custom-price-set
        // $params['price']='100';
        //productId
        $skuId =$_GET['sku'];
        // $_product = $this->productFactory->loadByAttribute('sku', $sku);
        $_product = $this->productRepository->get($skuId);
        // $_product = $this->product->load($pId);

        if ($_product){
            $this->cart->addProduct($_product, $params);
            $this->cart->save();
        }

        $this->messageManager->addSuccess(__('Add to cart successfully.'));
    } catch (\Magento\Framework\Exception\LocalizedException $e) {
        $this->messageManager->addException(
            $e,
            __('%1', $e->getMessage())
        );
    } catch (\Exception $e) {
        $this->messageManager->addException($e, __('error.'));
    }
    /*cart page*/
    $this->getResponse()->setRedirect('/checkout/cart/');
  }
}
moazzams
  • 87
  • 2
  • 9
0
save the product through
<?php

namespace Indexiz\Addtocart\Controller\Index;

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

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

    protected $productRepository;

    // protected $_productFactory;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        \Magento\Catalog\Model\Product $product,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        // \Magento\Catalog\Model\ProductFactory $_productFactory,
        \Magento\Checkout\Model\Cart $cart
    ) {
        $this->resultPageFactory = $resultPageFactory;
        $this->cart = $cart;
        $this->product = $product;
        $this->productRepository = $productRepository;
        // $this->productFactory = $_productFactory;
        parent::__construct($context);
    }
    public function execute()
    {
        try {
            $params = array();
            $params['qty'] = '1';//product quantity
            /*get product id*/
            // custom-price-set
            // $params['price']='100';
            //productId
            $skuId =$_GET['sku'];
            // $_product = $this->productFactory->loadByAttribute('sku', $sku);
            $_product = $this->productRepository->get($skuId);
            // $_product = $this->product->load($pId);

            if ($_product){
                $this->cart->addProduct($_product, $params);
                $this->cart->save();
            }

            $this->messageManager->addSuccess(__('Add to cart successfully.'));
        } catch (\Magento\Framework\Exception\LocalizedException $e) {
            $this->messageManager->addException(
                $e,
                __('%1', $e->getMessage())
            );
        } catch (\Exception $e) {
            $this->messageManager->addException($e, __('error.'));
        }
        /*cart page*/
        $this->getResponse()->setRedirect('/checkout/cart/');
    }
}
moazzams
  • 87
  • 2
  • 9
0
<?php $buttonBuyNow = __('Buy Now'); ?>
<?php $_product = $block->getProduct(); 
    $sku=$_product->getSku();
?>
<a href="addtocart?sku=<?php echo $sku; ?> "   title="">
                <div class="actions">
                    <button type="submit" value="<?= /* @escapeNotVerified */ $buttonBuyNow ?>" class="action primary-data tocart" id="product-addtocart-button"><?= /* @escapeNotVerified */ $buttonBuyNow ?></button>
                </div>
            </div>
</a>

<style type="text/css" media="screen">
    .primary-data{
        display: inline-block;
    height: 52px;
    min-width: 200px;
    text-align: center;
    border-radius: 2px;
    text-transform: capitalize;
    font-weight: 500;
    border: 1px solid #ed2228;
    background-color: #ed2228;
    color: #fff;
    margin-right: 20px;
    margin-bottom: 10px;
}
</style>
moazzams
  • 87
  • 2
  • 9