Magento2.4 Add Product to Cart with Customizable Option – How to Guide

addtocartcustomizable-optionsmagento2phtml

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.

Best Answer

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

Related Topic