2

We have a requirement that we wants to add product to cart programmatically in magento2.

marked as duplicate by Prince Patel, Qaisar Satti, Siarhey Uchukhlebau, sv3n, liyakat Aug 25 '17 at 4:05

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

7
protected $formKey;   
protected $cart;
protected $product;

public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Data\Form\FormKey $formKey,
\Magento\Checkout\Model\Cart $cart,
\Magento\Catalog\Model\Product $product,
array $data = []) {
    $this->formKey = $formKey;
    $this->cart = $cart;
    $this->product = $product;      
    parent::__construct($context);
}

public function execute()
 { 
  $productId =10;
  $params = array(
                'form_key' => $this->formKey->getFormKey(),
                'product' => $productId, //product Id
                'qty'   =>1 //quantity of product                
            );              
    //Load the product based on productID   
    $_product = $this->product->load($productId);       
    $this->cart->addProduct($_product, $params);
    $this->cart->save();
 }
  • Do we need to pass the customer id here? – srg Aug 24 '17 at 4:55
  • no need @srg please place the 'code' in your custom controller and submit the form – Nagaraju Kasa Aug 24 '17 at 4:57
  • so how can we identify the product is added to which customer cart? – srg Aug 24 '17 at 4:58
  • ok let me check and update you, before that please try with the above code and comment me with u required details – Nagaraju Kasa Aug 24 '17 at 5:02
  • 2
    the above code is adding product to guest cart succesfully. can you help me to add product to a registered customer cart using customer id or something like that? – srg Aug 24 '17 at 5:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.