How to add a custom columns to the Magento 2 products grid?

How To Add Custom Column In Magento 2 Products Grid

Any value you want to add to a product and display it in the product grid is not too difficult. You can do this, by following steps:

How to add a column in product:

Step 1 : Create a module

First, you have to create module. For that you need to crate a registration.php and module.xml . We will start with registration.php, create this file in app/code/Bay20/Custom directory. Here Bay20 is vendor name and Custom is module name.

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Bay20_Custom',
    __DIR__
);

now create app/code/Bay20/Custom/etc/module.xml.

<?xml version="1.0" encoding="utf-8" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Bay20_Custom" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Catalog"/>
        </sequence>
    </module>
</config>

After creating both the files, run the commands,

php bin/magento module:enable Bay20_CustomColumn

and

php bin/magento setup:upgrade

Step 2 : Add custom column to product grid

To create custom column, you need listing UI component instance named Product_listing and xml configuration file Magento_Catalog/view/adminhtml/ui_component/product_listing.xml.

To customize this file, you need to create a file in app/code/Bay20/Custom/view/adminhtml/ui_component/product_listing.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="product_columns"> 
        <column name="manage_stock" component="Magento_Ui/js/grid/columns/select" sortOrder="76"> 
            <settings> 
                <addField>true</addField> 
                <options class="Magento\Config\Model\Config\Source\Yesno"/> 
                <filter>select</filter> 
                <dataType>select</dataType> 
                <sortable>false</sortable> 
                <label translate="true">Manage Stock</label> 
            </settings> 
        </column> 
    </columns> 
</listing>

After adding code, run this command to clean the cache:

php bin/magento cahe:clean

Once cache is cleaned, you can check a custom column has been created in the product table.

Step 3 : Add data to product collection

To add stock related data to products collection, data provider class is used for product_listing instance

Magento_Catalog/view/adminhtml/ui_component/product_listing.xml

<dataSource name="product_listing_data_source" component="Magento_Ui/js/grid/provider"> 
    <settings> 
        <storageConfig> 
            <param name="dataScope" xsi:type="string"> filters.store_id</param> 
        </storageConfig> 
        <updateUrl path="mui/index/render"/> 
    </settings> 
    <aclResource>Magento_Catalog::products</aclResource> 
    <dataProvider class="Magento\Catalog\Ui\DataProvider\Product\ProductDataProvider" name="product_listing_data_source"> 
        <settings> 
            <requestFieldName>id</requestFieldName> 
            <primaryFieldName>entity_id</primaryFieldName> 
        </settings> 
    </dataProvider> 
</dataSource>

You can check that, dataProvider is a class of dataSource UI component.

Data provider class has two classes addFieldStrategies and addFilterStrategies . addField and addFilter are two methods of two classes respectively.

Manage stock field strategy

This strategy will allow to add stock management status to product collection is first thing that you need to do.

Bay20\Custom\Ui\DataProvider\Product\AddManageStockFieldToCollection

<?php 
namespace Bay20\Custom\Ui\DataProvider\Product; 
class AddManageStockFieldToCollection implements \Magento\Ui\DataProvider\AddFieldToCollectionInterface 
{ 
    public function addField(\Magento\Framework\Data\Collection $collection, $field, $alias = null) 
    { 
        $collection->joinField('manage_stock', 'cataloginventory_stock_item', 'manage_stock', 'product_id=entity_id', null, 'left'); 
    } 
}

addField method from AddFieldToCollectionInterface will implement AddManageStockFieldToCollection strategy.Stock management column comes from cataloginventory_Stock_itemwhich is a table in DB and manage_stock is a column of that table.

Manage stock filter strategy

If you want to filter grid data by stock management status then you you need a stock filter strategy.

Bay20\Custom\Ui\DataProvider\Product\AddManageStockFilterToCollection

<?php 
namespace Bay20\Custom\Ui\DataProvider\Product; 
class AddManageStockFilterToCollection implements \Magento\Ui\DataProvider\AddFilterToCollectionInterface 
{ 
    public function addFilter(\Magento\Framework\Data\Collection $collection, $field, $condition = null) 
    { 
        if (isset($condition['eq'])) { 
            $collection->addFieldToFilter($field, $condition); 
        } 
    } 
}

addFilter method from AddFilterToCollectionInterface will implement AddManageStockFilterToCollection strategy.

Add strategies to the product listing data provider

After creating these strategies, now add these strategies in product_listing data provider to use them. For this create , app/code/Bay20/Custom/etc/adminhtml/di.xml

<?xml version="1.0" encoding="utf-8" ?> 
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> 
    <type name="Magento\Catalog\Ui\DataProvider\Product\ProductDataProvider"> 
        <arguments> 
            <argument name="addFieldStrategies" xsi:type="array"> 
                <item name="manage_stock" xsi:type="object">Bay20\Custom\Ui\DataProvider\Product\AddManageStockFieldToCollection</item> 
            </argument> 
            <argument name="addFilterStrategies" xsi:type="array"> 
                <item name="manage_stock" xsi:type="object">Bay20\Custom\Ui\DataProvider\Product\AddManageStockFilterToCollection</item> 
            </argument> 
        </arguments> 
    </type> 
</config>

Once you done with all these steps, don’t forget to clean cache,

php bin/magento cache:clean config

After executing this command, you can check the custom column is added with data.

Conclusion:

Sometimes you have to display product attributes in the tables and also column which is not product attribute. At that time you create a custom column.