Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento 2 add product to cart programmatically with custom options

Tags:

php

magento2

I have created one test script file for add product into cart with custom options. I want display selected custom option of product in cart using programmatically.

Please check my below code:

$productId = 25;
$product = $objectManager->create('\Magento\Catalog\Model\Product')->load($productId);
$cart = $objectManager->create('Magento\Checkout\Model\Cart');  
$params = array();      
$params['options[469]'] = 459;
$params['qty'] = 1;
$params['product'] = 25

$cart->addProduct($product, $params);
$cart->save();

Using objectmanager i have created cart and product object. When i have fired this script in browser, it's show me error:

Magento\Framework\Exception\LocalizedException: Please specify product's required option(s).

I have already passed custom option in params array. but still it's show error.

How can i add product into cart with selected custom options ?

Please help me.

Any help would be appreciated.

like image 938
Niks Avatar asked Jan 17 '18 09:01

Niks


2 Answers

I have got the solution of this problem. Here is my updated code.

$productId = 127;
$product = $obj->create('\Magento\Catalog\Model\Product')->load($productId);

$cart = $obj->create('Magento\Checkout\Model\Cart');    
$params = array();      
$options = array();
$params['qty'] = 1;
$params['product'] = 127;

foreach ($product->getOptions() as $o) 
{       
    foreach ($o->getValues() as $value) 
    {
        $options[$value['option_id']] = $value['option_type_id'];

    }           
}

$params['options'] = $options;
$cart->addProduct($product, $params);
$cart->save();

This code is work for me.

like image 90
Niks Avatar answered Sep 28 '22 02:09

Niks


please replace your code :

$productId = 25;
$product = $objectManager->create('\Magento\Catalog\Model\Product')->load($productId);
$cart = $objectManager->create('Magento\Checkout\Model\Cart');  
$params = array();      
$params['options[469]'] = 459;
$params['qty'] = 1;
$params['product'] = 25

$cart->addProduct($product, $params);
$cart->save();

Replace with

$productId = 25;
$product = $objectManager->create('\Magento\Catalog\Model\Product')->load($productId);
$cart = $objectManager->create('Magento\Checkout\Model\Cart');  
$formKey = $objectManager->create('\Magento\Framework\Data\Form\FormKey')->getFormKey();  
$option = array('469'=>459);

$params = array(
                    'form_key' => $formKey,
                    'product' => $productId, //product Id
                    'qty'   =>1, //quantity of product                
                    'options' => $option
                    );
$cart->addProduct($product, $params);
$cart->save();
like image 39
Charvi Avatar answered Sep 28 '22 02:09

Charvi