1

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?

1 Answer 1

5

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='Magento\Quote\Model\Quote\Item\ToOrderItem'>
        <plugin name='AddOrderItemPlugin' type='Vendorname\Module\Plugin\Model\Quote\Item\ToOrderItem' sortOrder='99'/>
    </type>
</config>

Now add a file Vendorname\Module\Plugin\Model\Quote\Item\ToOrderItem.php

<?php 
namespace Vendorname\Modulename\Plugin\Model\Quote\Item;

    class ToOrderItem {

        /**
         *
         * @var type \Magento\Catalog\Model\Product
         */
        protected $productRepository;

        /**
         * @param \Magento\Catalog\Model\Product $productRepository 
         */
        public function __construct(
        \Magento\Catalog\Model\Product $productRepository 
        ) {
            $this->productRepository = $productRepository;
        }

        /**
         * 
         * @param \Magento\Quote\Model\Quote\Item\ToOrderItem $subject
         * @param \Vendorname\Modulename\Plugin\Model\Quote\Item\callable $proceed
         * @param \Magento\Quote\Model\Quote\Item\AbstractItem $item
         * @param type $additional
         * @return type
         */
        public function aroundConvert(
        \Magento\Quote\Model\Quote\Item\ToOrderItem $subject, callable $proceed, \Magento\Quote\Model\Quote\Item\AbstractItem $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;
        }

    }
0

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.