19

I've added a new column to the table sales_order called export_status, now I want to add new order grid column with the data from the new sales_order column.

I've managed to add column to the sales_order_grid table.

$installer->getConnection()->addColumn($installer->getTable("sales_order_grid"), "xml_exported", [
     'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
     'comment' => 'XML Exported'
]);

How can I now make it actually show in the orders grid with the value from the sales_order export_status column?

41

After lots of digging in magento core code I found a solution for my question. Instead of adding a column to the grid via the database, I created a UI component sales_order_grid.xml under [COMPANY]/[MODULE]/view/adminhtml/ui_component/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="[COMPANY]\[MODULE]\Ui\Component\Listing\Column\Status">
            <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">XML Exported</item>
                </item>
            </argument>
        </column>
    </columns>
</listing>

Then created the UI class under [COMPANY]/[MODULE]/Ui/Component/Listing/Column/Status.php

namespace [COMPANY]\[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 Status 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("export_status");

                switch ($status) {
                    case "0":
                        $export_status = "No";
                        break;
                    case "1";
                        $export_status = "Yes";
                        break;
                    default:
                        $export_status = "Failed";
                        break;

                }

                // $this->getData('name') returns the name of the column so in this case it would return export_status
                $item[$this->getData('name')] = $export_status;
            }
        }

        return $dataSource;
    }
}
  • This worked great. I'm facing an issue where this customization causes the toolbar of the order grid to be rendered after the grid. Did you experience this issue? – Ian Sep 27 '16 at 1:14
  • @Ian I did not have that issue. Which version of magento 2 are you using? – André Ferraz Sep 27 '16 at 10:07
  • 2
    CE 2.1.1. I determined the issue. My module came before Magento_Sales alphabetically. I added <sequence> with a dependency to Magento_Sales, disabled my module and then re-enabled it. This corrected the issue. – Ian Sep 28 '16 at 0:20
  • 1
    Does this work for export options also? In my case exported data had empty values. – MagePsycho Feb 19 '17 at 12:42
  • 1
    Likewise Magento 1's filter_condition_callback where you can add your own custom filter as per field. Please don't say "What do you mean?" this time ;) – MagePsycho Mar 7 '17 at 7:55
32

My solution may be a bit more efficient since it follows the native way of adding a column to the grid, and you won't have to load every order displayed on the page to obtain the column data (utilising the sales_order_grid table instead). The above is a great example of how to create a customised renderer though.

vendor/[vendor]/[package]/view/adminhtml/ui_component/sales_order_grid.xml

<!-- Add the column "my_column" (My Column) to the sales order grid. -->
<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="my_column">
        <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>
</columns>

Please note that you must enable the column using the drop-down widget above the order grid before it appears.

vendor/[vendor]/[package]/etc/di.xml

<!-- Sync the column "my_column" between the sales_order and sales_order_grid tables -->
<virtualType name="Magento\Sales\Model\ResourceModel\Order\Grid" type="Magento\Sales\Model\ResourceModel\Grid">
    <arguments>
        <argument name="columns">
            <item name="my_column" xsi:type="string">sales_order.my_column</item>
        </argument>
    </arguments>
</virtualType>

Sample setup code to add column to sales_order_grid table (use this in your install/upgrade script). The same code works for the sales_order table by the way.

$setup->getConnection()->addColumn(
        $setup->getTable('sales_order_grid'),
        'my_column',
        [
            'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            'length' => 255,
            'nullable' => true,
            'comment' => 'My Column'
        ]
    );

Hope it helps! :-)

  • This answer requires that the column is sales_order_grid table, correct? – Tero Lahtinen Jan 25 '18 at 15:18
  • @MageParts, when this script will work ? – SagarPPanchal Jun 20 '18 at 10:20
  • 1
    worked for me, thanks :3 btw, in that sales_order_grid.xml you should close your <listing></listing> tag or it will return an error of xml – fudu Sep 30 '18 at 2:11
  • <argument name="columns"> should be replaced with <argument name="columns" xsi:type="array"> in the di:xml file. Otherwise it will return the following error. Invalid Document Element 'argument': The type definition is abstract. – saiid Nov 19 '18 at 2:24
1

For creating a new column in order grid , I have referred Magento Default Module vendor/magento/module-customer-balance

In my case,'custom_column' column already exists in the sales_order table.

I have to show 'custom_column' column in order grid

Step 1: Add a new Column in sales_order_grid table

        $connection = $installer->getConnection();
        if ($connection->isTableExists('sales_order_grid')) {
            $connection->addColumn(
                $connection->getTableName('sales_order_grid'),
                'custom_column',
                [
                    "type"      =>  Table::TYPE_TEXT,
                    'default'   =>  null,
                    "comment"   =>  'Custom Column'
                ]
            );
    }

Step 2 : di.xml file in app\code[Vendor][NameSpace]\etc\di.xml

 <!-- Adding Columns in sales_order_grid-->
    <virtualType name="Magento\Sales\Model\ResourceModel\Order\Grid">
        <arguments>
            <argument name="columns" xsi:type="array">
                <item name="custom_column" xsi:type="string">sales_order.custom_column</item>
            </argument>
        </arguments>
    </virtualType>
    <virtualType name="Magento\SalesArchive\Model\ResourceModel\Order\Grid">
        <arguments>
            <argument name="columns" xsi:type="array">
                <item name="custom_column" xsi:type="string">sales_order.custom_column</item>
            </argument>
        </arguments>
    </virtualType>

Step 3 : Create sales_order_grid.xml layout file under app\code[Vendor][NameSpace]\view\adminhtml\ui_component

<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="custom_column">
            <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">Custom Column</item>
                </item>
            </argument>
        </column>
    </columns>
</listing>

Note: This has been tested in Magento version 2.2.6

0

Demo/ExtendedGrid/view/adminhtml/ui_component/sales_order_grid.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<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="new_column_name" class="Demo\ExtendedGrid\Ui\Component\Listing\Column\NewColumnStatus">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="sortable" xsi:type="boolean">false</item>
                    <item name="has_preview" xsi:type="string">1</item>
                    <item name="label" xsi:type="string" translate="true">New Column Name</item>
              </item>
            </argument>
        </column>
    </columns>
</listing>

Then Created the UI Class to render it.

Demo/ExtendedGrid/Ui/Component/Listing/Column/NewColumnStatus.php

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Demo\ExtendedGrid\Ui\Component\Listing\Column;

/**
 * Class  NewColumnStatus
 */
class NewColumnStatus extends \Magento\Ui\Component\Listing\Columns\Column
{

    /**
     * @var string[]
     */
    protected $statuses;

   /**
     * Constructor
     *
     * @param ContextInterface $context
     * @param UiComponentFactory $uiComponentFactory
     * @param CollectionFactory $collectionFactory
     * @param array $components
     * @param array $data
     */
       public function __construct(
        \Magento\Framework\View\Element\UiComponent\ContextInterface $context,
        \Magento\Framework\View\Element\UiComponentFactory $uiComponentFactory,
        \Magento\Framework\UrlInterface $urlBuilder,
        array $components = [],
        array $data = []
    ) {
        $this->urlBuilder = $urlBuilder;
         parent::__construct($context, $uiComponentFactory, $components, $data);
    }


    /**
     * Prepare Data Source
     *
     * @param array $dataSource
     * @return void
     */
    public function prepareDataSource(array $dataSource)
    {
        if (isset($dataSource['data']['items'])) {
            foreach ($dataSource['data']['items'] as &$item) {

           //put  the logic here


            }
        }

        return $dataSource;
   }
}

Dont forget to clear cache.

-1

I have created custom module which will add custom attribute in Sales Order entity and then show in admin Sales Order grid.

module.xml file to define the module. app\code\COMPANY\MODULE\etc\module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="COMPANY_MODULE" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Sales"/>
            <module name="Magento_Quote"/>
            <module name="Magento_Checkout"/>
        </sequence>
    </module>
</config>

di.xml file in app\code\COMPANY\MODULE\etc\di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <virtualType name="Magento\Sales\Model\ResourceModel\Order\Grid" type="Magento\Sales\Model\ResourceModel\Grid">
        <arguments>
            <argument name="columns" xsi:type="array">
                <item name="export_status" xsi:type="string">sales_order.export_status</item>
            </argument>
        </arguments>
    </virtualType>
</config>

InstallData.php to add custom attribute export_status in database table

app\code\COMPANY\MODULE\Setup\InstallData.php

<?php

namespace COMPANY\MODULE\Setup;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

/**
 * @codeCoverageIgnore
 */
class InstallData implements InstallDataInterface
{
    /**
     * EAV setup factory
     *
     * @var EavSetupFactory
     */
    private $eavSetupFactory;

    /**
     * Init
     *
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        if (version_compare($context->getVersion(), '1.0.0') < 0){      
            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $salesSetup = $objectManager->create('Magento\Sales\Setup\SalesSetup');
            $salesSetup->addAttribute('order', 'export_status', ['type' =>'varchar']);
            $quoteSetup = $objectManager->create('Magento\Quote\Setup\QuoteSetup'); 
        }
    }
}

sales_order_grid.xml to add custom column in Sales Order admin grid.

<?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">
            <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">XML Exported</item>
                </item>
            </argument>
        </column>
    </columns>
</listing>

You can download the full module by clicking on below link http://vdcstaging.co.in/download/add-custom-culumn-to-admin-grid.zip

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.