In this post, we will learn how to add a custom column in sales order grid in Magento 2.
In Magento 2 store owner has the necessity of getting extra information like customer comments. But just receiving such information and saving it into the database is not helpful. Because all time you need to navigate in backend order details views to see selected information. Instead, adding one extra column in Backend Sales Order Grid will help you to have quick look at all useful information.
Steps to add a custom column in order grid in Magento 2 :
Firstly, we need to create a “sales_order_grid.xml” file at this path using the below code.
app\code\Webiators\OrderColumn\view\adminhtml\ui_component\
1
2
3
4
5
6
7
8
9
10
11
|
<listing xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=“urn:magento:module:Magento_Ui:etc/ui_configuration.xsd”>
<columns name=“sales_order_columns”>
<column name=“newfield” class=“Webiators\OrderColumn\Ui\Component\Listing\Column\Mycolumn”>
<argument name=“data” xsi:type=“array”>
<item name=“config” xsi:type=“array”>
<item name=“filter” xsi:type=“string”>text</item>
<item name=“label” xsi:type=“string” translate=“true”>My Column</item>
</item>
</argument>
</column>
</listing>
|
Now you have to create one more file “Mycolumn.php” at the following location.
app\code\Webiators\OrderColumn\Ui\Component\Listing\Column\
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
<?php
namespace Webiators\OrderColumn\Ui\Component\Listing\Column;
use \Magento\Sales\Api\OrderRepositoryInterface;
use \Magento\Framework\View\Element\UiComponent\ContextInterface;
use \Magento\Framework\View\Element\UiComponentFactory;
use \Magento\Ui\Component\Listing\Columns\Column;
use \Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Pricing\PriceCurrencyInterface;
class Mycolumn extends Column
{
protected $_orderRepository;
protected $_searchCriteria;
public function __construct(
PriceCurrencyInterface $priceCurrency,
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
OrderRepositoryInterface $orderRepository,
SearchCriteriaBuilder $criteria,
array $components = [],
array $data = [])
{
$this–>_orderRepository = $orderRepository;
$this–>_searchCriteria = $criteria;
$this–>priceCurrency = $priceCurrency;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource[‘data’][‘items’])) {
foreach ($dataSource[‘data’][‘items’] as & $item) {
$order = $this->_orderRepository->get($item[“entity_id”]);
$item[$this–>getData(‘name’)] = $order–>getData(“newfield”);
}
}
return $dataSource;
}
}
|
That’s it
If you are facing any issue while implementing this code feel free to mention them in the Comments section below.
Happy Coding!