Magento 2 copy value from custom attribute to order item

The question:

I have created a custom attribute for products. And I have also created an extra column in sales_order_item. How can I copy the value from this custom attribute to the new column in sales_order_item when an order is placed?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

You can use plugin to add custom attribute to sales_order_item when order is placed.
create a di.xml on under etc/di.xml.

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd" >
    <type name='MagentoQuoteModelQuoteItemToOrderItem'>
        <plugin name='AddOrderItemPlugin' type='VendornameModulePluginModelQuoteItemToOrderItem' sortOrder='99'/>
    </type>
</config>

Now add a file VendornameModulePluginModelQuoteItemToOrderItem.php

<?php 
namespace VendornameModulenamePluginModelQuoteItem;

    class ToOrderItem {

        /**
         *
         * @var type MagentoCatalogModelProduct
         */
        protected $productRepository;

        /**
         * @param MagentoCatalogModelProduct $productRepository 
         */
        public function __construct(
        MagentoCatalogModelProduct $productRepository 
        ) {
            $this->productRepository = $productRepository;
        }

        /**
         * 
         * @param MagentoQuoteModelQuoteItemToOrderItem $subject
         * @param VendornameModulenamePluginModelQuoteItemcallable $proceed
         * @param MagentoQuoteModelQuoteItemAbstractItem $item
         * @param type $additional
         * @return type
         */
        public function aroundConvert(
        MagentoQuoteModelQuoteItemToOrderItem $subject, callable $proceed, MagentoQuoteModelQuoteItemAbstractItem $item, $additional = []
        ) {

            $orderItem = $proceed($item, $additional);
            $productId = $item->getProduct()->getId();
            $product = $this->productRepository->load($productId);
            $supplier = $product->getSuppliers();//my custom product attribute
            $orderItem->setSupplierId($supplier);//saving into orde item in `supplier_id` column
            return $orderItem;
        }

    }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment