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?

asked Apr 4, 2017 at 13:05

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;
 }
 }
answered Dec 8, 2017 at 6:34
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.