skip to Main Content

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('MagentoCatalogModelProduct')->load($productId);
$cart = $objectManager->create('MagentoCheckoutModelCart');  
$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:

MagentoFrameworkExceptionLocalizedException: 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.

2

Answers


  1. Chosen as BEST ANSWER

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

    $productId = 127;
    $product = $obj->create('MagentoCatalogModelProduct')->load($productId);
    
    $cart = $obj->create('MagentoCheckoutModelCart');    
    $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.


  2. please replace your code :

    $productId = 25;
    $product = $objectManager->create('MagentoCatalogModelProduct')->load($productId);
    $cart = $objectManager->create('MagentoCheckoutModelCart');  
    $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('MagentoCatalogModelProduct')->load($productId);
    $cart = $objectManager->create('MagentoCheckoutModelCart');  
    $formKey = $objectManager->create('MagentoFrameworkDataFormFormKey')->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();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search