0

I'm trying to create an order programmatically. With simple products without custom options it already works like a charm. But when I try to add custom options I get the very specific error:

We found an invalid request for adding product to quote.

Here is my foreach adding the products to quote

foreach($orderData['items'] as $item){
     $product=$this->_product->load($item['product_id']);
     $product->setPrice($item['price']);
     $params = array();
     $options = array();
     $params['qty'] = intval($item['qty']);
     $params['product'] = $item['product_id'];
     $params['form_key'] = $this->formKey->getFormKey();
     if(array_key_exists("options", $item)){
          foreach($item["options"] as $value){
                $options[$value['option_id']] = ($value['option_type_id']);
          }
          $params['options'] = $options;
     }          
     $this->_logger->info("params: " . print_r($params, true));          
     $quote->addProduct($product, $params);
}

The Log entry for $params shows this (which looks correct to me according to every tutorial I could find on this):

[2019-01-21 14:56:08] main.INFO: params: Array
(
    [qty] => 1
    [product] => 3392
    [form_key] => LQbWtaWdFhvMDD3h
    [options] => Array
        (
            [110465] => 239176
            [110466] => 239179
            [110467] => 239185
            [110468] => 239190
            [110469] => 239192
            [110470] => 239196
        )

)

[options]['key'] is the option's Id, [options]['key'] => $value is the option's value's Id (which is correct, triple checked it).

Does anybody have an idea where my mistake is? Or for that matter, how to debug it further? Because trying to catch the exception results in the same Error Message which, like I already said, is not very specific.

1 Answer 1

0

I've found the solution myself. After digging a little I discovered that addProduct() expects a DataObject. So I replaced my foreach with the following. Works for me, hope this might help somebody. Note that I dropped the formkey since it is not needed in admin.

foreach($orderData['items'] as $item){

     $product = $objectManager->create('\Magento\Catalog\Model\Product')->load($item['product_id']);
     $product->setPrice($item['price']);

     $params = new \Magento\Framework\DataObject();
     $params->setQty($item['qty']);

     $options = array();

     if(array_key_exists("options", $item)){
         foreach($item["options"] as $value){
             $options[$value['option_id']] = $value['option_type_id'];
         }
         $params->setOptions($options);
     } 
     $quote->addProduct($product, $params);
 }

Your Answer

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

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