0

I have a simple product with a configuration option. The SKU of my product is configurator and the SKU of the options is configuration. The configuration option is a string field.

To add the product to my cart I use the following code.

$product = $this->getProductBySku('configurator');
$option = $this->getOptionBySku($product, 'configuration');
$product->addCustomOption('option_ids', $option->getData('option_id'));
$product->addCustomOption('option_1', $this->fetchConfigCode());

$this->cart->addProduct($product, [
     'product_id' => $product->getId(),
     'qty' => 1,
]);

$this->cart->save();

When I dump($this->cart->getItems()), I can just see my product living in my cart just fine. But after I reload and something reads from the cart, it throws the following error.

Uncaught Error: Call to a member function getValue() on null in /var/www/html/vendor/magento/module-catalog/Model/Product/Type/AbstractType.php:819
Stack trace:
#0 /var/www/html/vendor/magento/module-catalog/Model/Product/Type/AbstractType.php(790): Magento\Catalog\Model\Product\Type\AbstractType->getOptionSku(Object(Magento\Catalog\Model\Product\Interceptor), 'configurator')
#1 /var/www/html/vendor/magento/module-catalog/Model/Product.php(1931): Magento\Catalog\Model\Product\Type\AbstractType->getSku(Object(Magento\Catalog\Model\Product\Interceptor))
#2 /var/www/html/vendor/magento/module-quote/Model/Quote/Item.php(431): Magento\Catalog\Model\Product->getSku()
#3 /var/www/html/vendor/magento/module-quote/Model/ResourceModel/Quote/Item/Collection.php(274): Magento\Quote\Model\Quote\Item->setProduct(Object(Magento\Catalog\Model\Product\Interceptor))
#4 /var/www/html/vendor/magento/module-quote/Model/ResourceModel/Quote/Item/Collection.php(204): Magento\Quote\Model\ResourceModel\Quote\Item\Collection->_assignPr in 

Deleting the session (thus emptying the cart) removes the error again, until I add the product again.

Is this a bug in Magento? Did I add my product incorrectly?

0

The problem lies in

$product->addCustomOption('option_1', $this->fetchConfigCode());

You're adding the wrong option id. Magento is looking for the value for the option id of $option->getData('option_id') but is finding only 1 instead. change it to:

$product->addCustomOption('option_'. $option->getData('option_id'), $this->fetchConfigCode());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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