3

I used this to Add Additional Options In Magento 2 Cart

https://livesubwpcache.cloudways.com/blog/add-additional-options-in-magento-2/

But this is working only with Simple product.

For configurable products, I did the following change

$item->addOption(array(
    'product_id' => $item->getProductId(),
    'code' => 'additional_options',
    'value' => serialize($additionalOptions)
));

After that, the additional_options going to the cart. But it is not getting saved when complete the order.

seems because of this ….

//filter out config/bundle etc product
if(!$item->getParentItemId() && $item->getProductType() == \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
{
    $this->quoteItems[$item->getId()] = $item;
}

How can I fix it ? I need this functionality for configurable products.

3 Answers 3

5

after $item->addOption(...) try calling $item->saveItemOptions().
Also a side note, don't add the options as serialized using serialize($additionalOptions), use json_encode or better yet the method Magento\Framework\Serialize\Serializer\Json::serialize.

2

Step 1: Create registration.php and module.xml file the for custom module.

Step 2: Assign Observers to Events

/app/code/Namespace/Mymodule/etc/events.xml

    <?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="catalog_product_load_after">
        <observer name="set_additional_options" instance="Namespace\Mymodule\Observer\SetAdditionalOptions"/>
    </event>
</config>

Step 3: Create the Observers

app/code/Namespace/Mymodule/Observer/SetAdditionalOptions.php

<?php
namespace Namespace\Mymodule\Observer;
 
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Serialize\SerializerInterface;
 
class SetAdditionalOptions implements ObserverInterface
{
    /**
     * @var RequestInterface
     */
    protected $_request;
     
    /**
     * @param RequestInterface $request
     */
    public function __construct(
        RequestInterface $request,
        SerializerInterface $serializer
    ) {
        $this->_request = $request;
        $this->serializer = $serializer;
    }
 
    /**
     * @param \Magento\Framework\Event\Observer $observer
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        // Check and set information according to your need
        if ($this->_request->getFullActionName() == 'checkout_cart_add') { //checking when product is adding to cart
            $product = $observer->getProduct();
            $additionalOptions = [];
            $additionalOptions[] = array(
                'label' => 'Some Label',
                'value' => 'Some Info',
            );
            $observer->getProduct()->addCustomOption('additional_options', $this->serializer->serialize($additionalOptions));
        }
    }
}

run below command after

rm -rf var/di var/generation var/cache/* var/log/* var/page_cache/*

php bin/magento setup:upgrade

php bin/magento setup:di:compile

php bin/magento cache:clean

php bin/magento cache:flush

php bin/magento indexer:reindex

reference links

https://www.cloudways.com/blog/add-additional-options-in-magento-2/

https://webkul.com/blog/additional-options-cart-item-magento2/

https://www.codedecorator.com/blog/how-to-additional-options-in-cart-item-magento2/ (Magento2.4)

5
  • Thanks for your answer. But still the same issue. The additional options not in the back-end when I order configurable products. Commented Jun 30, 2017 at 12:12
  • @SamanthaRajasingha - Can you refer the above both links?
    – Jjo
    Commented Jun 30, 2017 at 12:14
  • I used those links already, I got the same issue from there. Commented Jun 30, 2017 at 12:19
  • how to add additional options from the controller by item id in magento 2 Commented Oct 30, 2018 at 15:26
  • @SamanthaRajasingha, have you fixed the issue. I am facing same issue with additional options which is not showing in admin Commented Sep 30, 2019 at 12:32
0

After add additional options to cart You need to create another observer for save additional attributes order item from quote item.

Please add this event observer code in Module's etc/events.xml

<event name="sales_model_service_quote_submit_before">
    <observer instance="Vendor\Module\Observer\Sales\OrderItemAdditionalOptions" name="vendor_module_observer_sales_model_service_quote_submit_before"/>
</event>

Please create observer file in your module

Vendor\Module\Observer\Sales\OrderItemAdditionalOptions.php

And here is Observer code for save Additional Options to Order Item.

<?php
namespace Vendor\Module\Observer\Sales;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Serialize\Serializer\Json;
class OrderItemAdditionalOptions implements ObserverInterface
{
public function __construct(
Json $serializer = null
) {    
    $this->serializer = $serializer ?: ObjectManager::getInstance()->get(Json::class);
}
/**
 * @param \Magento\Framework\Event\Observer $observer
 */
public function execute(\Magento\Framework\Event\Observer $observer)
{
    try {
        $quote = $observer->getQuote();
        $order = $observer->getOrder();
        $quoteItems = [];

        // Map Quote Item with Quote Item Id
        foreach ($quote->getAllVisibleItems() as $quoteItem) {
            $quoteItems[$quoteItem->getId()] = $quoteItem;
        }

        foreach ($order->getAllVisibleItems() as $orderItem) {
            $quoteItemId = $orderItem->getQuoteItemId();
            $quoteItem = $quoteItems[$quoteItemId];
            $additionalOptions = $quoteItem->getOptionByCode('additional_options');


            if (count($additionalOptions) > 0) {
                // Get Order Item's other options
                $options = $orderItem->getProductOptions();
                // Set additional options to Order Item
                $options['additional_options'] = $this->serializer->unserialize($additionalOptions->getValue());
                $orderItem->setProductOptions($options);
            }
        }
    } catch (\Exception $e) {
        // catch error if any
    }
}
}

Please check this I think it will help you.

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.