To add additional custom options to a Magento 2 order, you can follow these steps:
- Create a custom module: To create a custom module, you need to create a new directory in the
app/code
directory and create the required files for your module. - Add the custom option to the quote item: The custom option can be added to the quote item by using the
setProductOptions
method.
Here’s an example of how you can add the custom option to the quote item:
<?php namespace Vendor\Module\Observer; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; class AddCustomOptionToOrder implements ObserverInterface { public function execute(Observer $observer) { $quoteItem = $observer->getQuoteItem();
$product = $quoteItem->getProduct();
$options = $product->getTypeInstance()->getOrderOptions($product);
$options['custom_option'] = 'custom_value';
$quoteItem->setProductOptions($options);
}
}
- Add the custom option to the order item: The custom option can be added to the order item by using the
setProductOptions
method.
Here’s an example of how you can add the custom option to the order item:
<?php namespace Vendor\Module\Observer; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; class AddCustomOptionToOrder implements ObserverInterface { public function execute(Observer $observer) { $orderItem = $observer->getOrderItem();
$quoteItem = $observer->getQuoteItem();
$options = $quoteItem->getProduct()->getTypeInstance()->getOrderOptions($quoteItem->getProduct());
$options['custom_option'] = 'custom_value';
$orderItem->setProductOptions($options);
}
}
- Update the di.xml file: You need to update the di.xml file to register the observer.
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="sales_model_service_quote_submit_before">
<observer name="vendor_module_add_custom_option_to_order" instance="Vendor\Module\Observer\AddCustomOptionToOrder"/>
</event>
</config>
- Flush Magento cache: Finally, flush the Magento cache by running the following command in the terminal:
php bin/magento cache:flush
.