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.
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.
Best Answer
Wrong
Right
Hard Coded:
Dynamic:
The key: 2 is the optionTypeId.
The val: 3 is the optionId.
Accessible by loading product by Id, ex:
You can also add the product to the cart and Inspect the Form Data Headers to see the option ID's: