How to Create Admin Grid in Magento 2

How to Create Admin Grid In Magento 2: Complete Guides

by nkhuyen

Creating an admin grid in Magento 2 is a crucial task for any Magento store owner or developer aiming to efficiently manage and display data within the admin panel. An admin grid provides a structured and user-friendly way to handle large volumes of data, such as product listings, customer information, and order details.

So, how to create admin grid in Magento 2? This guide will provide a step-by-step approach to building your admin grid via two methods.

Why Should Create Admin Grid in Magento 2?

Magento 2 grids serve as a mechanism for organizing items within a database table, facilitating enhanced management capabilities. These grids enable users to sort, filter, edit, and update data efficiently.

By default, Magento 2 includes various grids such as the order grid, product grid, and review grid. However, these standard grids may not suffice when there is a need to develop a custom grid for managing and displaying items from a custom module.

The appropriate approach is to establish an admin grid in Magento 2.

This functionality permits the creation and presentation of order or customer data in a tabular format tailored to user specifications.

In addition, it offers the capability to dynamically remove columns from the admin grid, thereby providing a more personalized and streamlined representation of the data.

Furthermore, it is essential to create an admin menu in Magento 2 to facilitate access to any custom pages within the admin panel.

There are two methods to programmatically create an admin grid in Magento 2: using Block and using UI components. Both approaches are discussed in the section below.

How to Create Admin Grid in Magento 2 Store with 2 Methods

Below are two methods to create an admin grid in Magento 2 Store:

Method 1. Using Block

1. Create Block file [Vendor]\[Module]\Block\Adminhtml\Grid\Grid.php

namespace [Vendor]\[Module]\Block\Adminhtml\Grid;
use Magento\Backend\Block\Widget\Grid\Extended;
use Magento\Backend\Block\Template\Context;
use Magento\Backend\Helper\Data;
use Magento\Framework\Registry;
use Magento\Framework\ObjectManagerInterface;
use [Vendor]\[Module]\Model\ResourceModel\Demo\CollectionFactory as DemoCollection;
// also you can use Magento Default CollectionFactory
class Grid extends Extended
{
    protected $registry;
    protected $_objectManager = null;
    protected $demoFactory;
    public function __construct(
        Context $context,
        Data $backendHelper,
        Registry $registry,
        ObjectManagerInterface $objectManager,
        DemoCollection $demoFactory,
        array $data = []
    ) {
        $this->_objectManager = $objectManager;
        $this->registry = $registry;
        $this -> demoFactory = $demoFactory;
        parent::__construct($context, $backendHelper, $data);
    }
    protected function _construct()
    {
        parent::_construct();
        $this->setId('index');
        $this->setDefaultSort('created_at');
        $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
    }
    protected function _prepareCollection()
    {
        $demo = $this->demoFactory->create()
            ->addFieldToSelect('*');
        $demo->addFieldToFilter('id', array('neq' => ''));
        $this->setCollection($demo);
        return parent::_prepareCollection();
    }
    protected function _prepareColumns()
    {
        $this->addColumn(
            'id',
            [
                'header_css_class' => 'a-center',
                'type' => 'checkbox',
                'name' => 'id',
                'align' => 'center',
                'index' => 'id',
            ]
        );
        $this->addColumn(
            'id',
            [
                'header' => __('ID'),
                'type' => 'number',
                'index' => 'id',
                'header_css_class' => 'col-id',
                'column_css_class' => 'col-id',
            ]
        );
        $this->addColumn(
            'name',
            [
                'header' => __('Name'),
                'type' => 'text',
                'index' => 'name',
                'header_css_class' => 'col-id',
                'column_css_class' => 'col-id',
            ]
        );
        $this->addColumn(
            'email',
            [
                'header' => __('Email'),
                'index' => 'email',
                'class' => '',
                'width' => '125px',
            ]
        );
        $this->addColumn(
            'created_at',
            [
                'header' => __('Created At'),
                'index' => 'created_at',
                'type' => 'datetime',
            ]
        );
        $this->addColumn(
            'action',
            [
                'header' => __('Action'),
                'width'     => '100px',
                'type'      => 'action',
                'getter'     => 'getId',
                'actions'   => [
                    [
                        'caption' => __('Action Name'),
                        'url' => ['base' => 'routeName/controller/actionName'],
                        'field'   => 'id'   // pass id as parameter
                    ]
                ],
                'filter'    => false,
                'sortable'  => false,
                'index' => 'id',
                'is_system' => true
            ]
        );
        return parent::_prepareColumns();
    }
    public function getGridUrl()
    {
        return $this->getUrl('*/*/actionName', ['_current' => true]);
    }
}

2. Create Admin Controller [Vendor]\[Module]\Controller\Adminhtml\Grid\Index.php

namespace [Vendor]\[Module]\Controller\Adminhtml\Grid;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
class Index extends Action
{
    protected $resultPageFactory;
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory
    )
    {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
    }
    public function execute()
    {
        $this->_view->loadLayout();
        $resultPage = $this->resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->prepend(__('Grid Title'));
        $resultPage->setActiveMenu('Vendor_Module::gridList_name');
        $resultPage->addBreadcrumb(__('Grid Name Process'), __('Grid Name List'));
        $this->_addContent($this->_view->getLayout()->createBlock('[Vendor]\[Module]\Block\Adminhtml\Grid\Grid'));
        $this->_view->renderLayout();
    }
    protected function _isAllowed()
    {
        return true;
    }
}

3. Create [Vendor]/[Extension]/view/adminhtml/layout/route_controller_grid.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <body>
         <referenceContainer name="content">
            <block class="[Vendor]\[Module]\Block\Adminhtml\Grid\Grid" name="grid_grid_listing"/>
         </referenceContainer>
    </body>
</page>

Method 2. Create Admin Grid Using UI Component

Here are 4 essential steps to Magento 2 create custom admin grid using UI Component, ensuring a well-structured and functional admin interface:

1. Create or add code in [Vendor]/[Extension]/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="Vendor]\[Module]\Model\ResourceModel\Extension\Grid\Collection" type="Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult">

        <arguments>
            <argument name="mainTable" xsi:type="string">mc_grid_data</argument>
            <argument name="resourceModel" xsi:type="string">Vendor\Extension\Model\ResourceModel\Extension</argument>
        </arguments>
    </virtualType>

    <type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
        <arguments>
            <argument name="collections" xsi:type="array">
                <item name="vendor_extension_grid_listing_data_source" xsi:type="string">Vendor\Extension\Model\ResourceModel\Extension\Grid\Collection</item>
            </argument>
        </arguments>
    </type>
</config>

2. Create xml [Vendor]/[Extension]/view/adminhtml/layout/route_controller_grid.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <update handle="styles"/>
    <body>
        <referenceContainer name="content">
            <uiComponent name="route_controller_grid_list"/>
        </referenceContainer>
    </body>
</page>

3. Create xml for ui component grid listing

[Vendor]/[Extension]/view/adminhtml/ui_component/route_controller_grid_list.xml

<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="urn:magento:framework:Ui/etc/ui_configuration.xsd">
    <argument name="data" xsi:type="array">
        <item name="js_config" xsi:type="array">
            <item name="provider" xsi:type="string">somename_grid_list.somename_grid_data_source</item>
            <item name="deps" xsi:type="string">somename_grid_list.somename_grid_data_source</item>
        </item>
        <item name="spinner" xsi:type="string">somenames_columns</item>
        <item name="buttons" xsi:type="array">
            <item name="add" xsi:type="array">
                <item name="name" xsi:type="string">add</item>
                <item name="label" xsi:type="string" translate="true">Add</item>
                <item name="class" xsi:type="string">primary</item>
                <item name="url" xsi:type="string">route/container/addrow</item>
            </item>
        </item>
    </argument>
    <dataSource name="somename_grid_data_source">
        <argument name="dataProvider" xsi:type="configurableObject">
            <argument name="class" xsi:type="string">
                Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider
            </argument>
            <argument name="name" xsi:type="string">somename_grid_list_data_source</argument>
            <argument name="primaryFieldName" xsi:type="string">id</argument>
            <argument name="requestFieldName" xsi:type="string">id</argument>
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="update_url" xsi:type="url" path="mui/index/render"/>
                </item>
            </argument>
        </argument>
        <argument name="data" xsi:type="array">
            <item name="js_config" xsi:type="array">
                <item name="component" xsi:type="string">Magento_Ui/js/grid/provider</item>
            </item>
        </argument>
    </dataSource>
    <container name="listing_top">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="template" xsi:type="string">ui/grid/toolbar</item>
                <item name="stickyTmpl" xsi:type="string">ui/grid/sticky/toolbar</item>
            </item>
        </argument>
        <bookmark name="bookmarks">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="component" xsi:type="string">Magento_Ui/js/grid/controls/bookmarks/bookmarks</item>
                    <item name="displayArea" xsi:type="string">dataGridActions</item>
                    <item name="storageConfig" xsi:type="array">
                        <item name="saveUrl" xsi:type="url" path="mui/bookmark/save"/>
                        <item name="deleteUrl" xsi:type="url" path="mui/bookmark/delete"/>
                        <item name="namespace" xsi:type="string">somename_grid_list</item>
                    </item>
                </item>
            </argument>
        </bookmark>
        <columnsControls name="columns_controls"/>
        <filterSearch name="fulltext"/>
        <filters name="listing_filters">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="storageConfig" xsi:type="array">
                        <item name="indexField" xsi:type="string">id</item>
                        <item name="provider" xsi:type="string">
                            somename_grid_list.somename_grid_list.listing_top.bookmarks
                        </item>
                        <item name="namespace" xsi:type="string">current.filters</item>
                    </item>
                    <item name="childDefaults" xsi:type="array">
                        <item name="provider" xsi:type="string">
                            somename_grid_list.somename_grid_list.listing_top.listing_filters
                        </item>
                        <item name="imports" xsi:type="array">
                            <item name="visible" xsi:type="string">
                                somename_grid_list.somename_grid_list.somenames_columns.${ $.index }:visible
                            </item>
                        </item>
                    </item>
                </item>
            </argument>
        </filters>
        <massaction name="listing_massaction">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="selectProvider" xsi:type="string">
                        somename_grid_list.somename_grid_list.somenames_columns.ids
                    </item>
                    <item name="component" xsi:type="string">Magento_Ui/js/grid/tree-massactions</item>
                    <item name="indexField" xsi:type="string">id</item>
                </item>
            </argument>
            <action name="delete">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="type" xsi:type="string">delete</item>
                        <item name="label" xsi:type="string" translate="true">Delete</item>
                        <item name="url" xsi:type="url" path="route/controller/massdelete"/>
                        <item name="confirm" xsi:type="array">
                            <item name="title" xsi:type="string" translate="true">Delete</item>
                            <item name="message" xsi:type="string" translate="true">Do you want to delete selected row
                                record?
                            </item>
                        </item>
                    </item>
                </argument>
            </action>
        </massaction>
        <paging name="listing_paging">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="storageConfig" xsi:type="array">
                        <item name="provider" xsi:type="string">
                            somename_grid_list.somename_grid_list.listing_top.bookmarks
                        </item>
                        <item name="namespace" xsi:type="string">current.paging</item>
                    </item>
                    <item name="selectProvider" xsi:type="string">
                        somename_grid_list.somename_grid_list.somenames_columns.ids
                    </item>
                </item>
            </argument>
        </paging>
    </container>
    <columns name="meetanshi_inquirys_columns">
        <selectionsColumn name="ids">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="indexField" xsi:type="string">dealer_id</item>
                    <item name="sorting" xsi:type="string">desc</item>
                    <item name="sortOrder" xsi:type="number">10</item>
                </item>
            </argument>
        </selectionsColumn>
        <column name="id">
            <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">ID</item>
                    <item name="sortOrder" xsi:type="number">20</item>
                </item>
            </argument>
        </column>
        <column name="name">
            <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">Name</item>
                    <item name="sortOrder" xsi:type="number">30</item></item>
            </argument>
        </column>
        <actionsColumn name="actions" class="Vendor\Module\Ui\Component\Listing\Grid\Column\Actions">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="resizeEnabled" xsi:type="boolean">false</item>
                    <item name="resizeDefaultWidth" xsi:type="string">107</item>
                    <item name="indexField" xsi:type="string">id</item>
                </item>
            </argument>
        </actionsColumn>
    </columns>
</listing>

4. Create Controller [Vendor]\[Module]\Controller\Adminhtml\Dir_name

namespace Vendor\Module\Controller\Adminhtml\Dir_name;
 
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
 
class Index extends Action
{
    protected $resultPageFactory;
 
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory
    )
    {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
    }
 
    public function execute()
    {
        $resultPage = $this->resultPageFactory->create();
        $resultPage->setActiveMenu('Vendor_Module::grid_list'); // ui component grid name
        $resultPage->getConfig()->getTitle()->prepend((__('Manage Grid List')));
        return $resultPage;
    }
 
    protected function _isAllowed()
    {
        return true;
    }
}

That’s all. Magento store owners can use any of the aforementioned methods to create an admin grid in Magento 2, facilitating the efficient management of the store’s database.

Best Solutions to Enhance Magento Admin Product Grid

This guide will provide valuable tips to improve your admin product grid, making it more user-friendly and productive. Let’s explore the following features to customize your grid to suit your specific needs:

Enhanced Product Grid for Magento 2 extension by BSS Commerce offers a comprehensive suite of 4 exceptional features designed to assist Magento store admins in organizing and modifying the product grid. This all-in-one tool elevates product management significantly, allowing administrators to save considerable time.

Magento 2 Enhanced Admin Product Grid Extension BSS Commerce



Highlight Features

1. Management Product Grid with Magento Admin Product Grid with Category

  • Enhance the product grid by adding two new columns: Category and Category ID.
  • Use drag-and-drop functionality to arrange these columns in the desired order.
  • Organize the products based on the values of Category and Category ID.
  • Modify the category for several products simultaneously through bulk actions.

Highlight features Magento 2 Enhanced Admin Product Grid Extension 1

2. Improvised filter

  • Filter products that belong to the exact Category or Category ID.
  • Filter products by similar Category and Category ID

Highlight features Magento 2 Enhanced Admin Product Grid Extension 3

3. Edit Product Grid Inline with Magento 2 Product Grid Inline Editor 

  • Revise product details directly within the grid.
  • Use seven editable input types: Text Field, Text Area, Price, Drop-down, Date, Multiple Select, and Yes/No.
  • Adjust product attributes within an individual cell.
  • Implement bulk modifications across several rows efficiently.
  • Use the inline editing feature for a diverse range of products.

Highlight features Magento 2 Enhanced Admin Product Grid Extension 4

4. Admin Product Preview Plus

  • View the frontend product category pages directly from the grid and the product edit pages.
  • Access the frontend CMS pages through the CMS editing interface.
  • Quickly navigate backend pages to update information.
  • Log in as customers on the frontend.

Highlight features Magento 2 Enhanced Admin Product Grid Extension 2

Wrapping Up

That’s all about how to create admin grid in Magento 2 store, along with tips to enhance admin product grid in Magento 2. Implementing a well-structured admin grid can significantly enhance data organization, improve user experience, and boost overall productivity. The ability to sort, filter, and edit data efficiently streamlines administrative tasks and ensures data accuracy and consistency.

On the other hand, to optimize time and effort for Magento 2 create custom admin grid, you can consider using our Magento Development Services. Our service is developed exclusively for Magento, offering effective and secure hosting services, thus, you can devote your efforts to business enhancement without worrying about the website’s performance and safety.

BSS Commerce trusts that these guidelines be beneficial for you. If you have any questions or need further assistance, feel free to reach out.

Next Reading Suggestions

© 2019 BSS Commerce owned by THANH CONG INTER ., JSC. All Rights Reserved.
Business registration certificate no. 0106064469 issued by Hanoi Department of Planning and Investment on 19 December 2019.
Legal Representative: Mr. Nguyen Quang Trung.