Magento 2 – Add New Column to Sales Order Grid

magento2sales-ordersales-order-grid

when order placed at that time in admin sales order check that there is a gift option available or not if it is available that dispaly "yes" in order grid column else display "no".

please see attachments for more.

please share any suggestion if you have.

1) image where gift option available

gift option available here

2) image where display "yes" in grid
enter image description here

thanks

Best Answer

I created a UI component sales_order_grid.xml under

[Vendor]/[Module]/view/adminhtml/ui_component/sales_order_grid.xml

and add the following code to your sales_order_grid.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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="export_status" class="[Vendor]\[Module]\Ui\Component\Listing\Column\Giftstatus">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="visible" xsi:type="boolean">true</item>
                    <item name="label" xsi:type="string" translate="true">Gift Option</item>
                </item>
            </argument>
        </column>
    </columns>
</listing>

Then created the UI class under

[Vendor]/[Module]/Ui/Component/Listing/Column/Giftstatus.php

add the following code to your Giftstatus.php:

<?php
namespace Vendor\Module\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;

class Giftstatus extends Column
{
    protected $_orderRepository;
    protected $_searchCriteria;

    public function __construct(ContextInterface $context, UiComponentFactory $uiComponentFactory, OrderRepositoryInterface $orderRepository, SearchCriteriaBuilder $criteria, array $components = [], array $data = [])
    {
        $this->_orderRepository = $orderRepository;
        $this->_searchCriteria  = $criteria;
        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"]);
                $status = $order->getData("gift_message_id");

                if($status){
                    $message = 'Yes';
                }
                else{
                    $message = 'No';
                }

                $item[$this->getData('name')] = $message;
            }
        }

        return $dataSource;
    }
}
Related Topic