1

I am trying to add a product to cart with a customizable option. I can add simple products, but I have not successfully been able to add a product with an option. The product will eventually be added dynamically but I just want a hard coded example right now to build off of.

Custom options are: enter image description here

I would prefer just a simple objectManager example that will work in a phtml file to keep things simple and straight forward. But I will appreciate/accept any answer that works.

My current code:

$productId = 4;
$obj = \Magento\Framework\App\ObjectManager::getInstance();
$product = $viewModel->getLoadProduct($productId);
$cart = $obj->create('Magento\Checkout\Model\Cart');    
$params = array();      
$params['qty'] = 10;
$params['product'] = $productId;
$options = array();
$options['title'] = 'Rustic';
$params['options'] = $options;
$cart->addProduct($product, $params);
$cart->save();

I get this error:

Exception #0 (Magento\Framework\Exception\LocalizedException): The product's required option(s) weren't entered. Make sure the options are entered and try again.
2
  • 1
    Have you tried adding the $params['title'] = ID of the option, instead of the label? Nov 7, 2021 at 22:46
  • This is what was needed: $params[$optionTypeId] = $optionId; // 2 and 3 in my case Nov 9, 2021 at 3:23

1 Answer 1

1

Wrong

$options['title'] = 'Rustic';

Right

Hard Coded:

$options[2] = 3;

Dynamic:

$options[$optionTypeId] = $optionId;

The key: 2 is the optionTypeId.

The val: 3 is the optionId.

Accessible by loading product by Id, ex:

$loadedProduct = $viewModel->getLoadProduct($loadedProductId);
foreach ($loadedProduct->getOptions() as $options) {
            $optionData = $options->getValues();
            foreach ($optionData as $data) {
                $customizableOptions = $data->getData();
                print_r($customizableOptions);
            }
        }

You can also add the product to the cart and Inspect the Form Data Headers to see the option ID's:

enter image description here

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.