MCPcopy Index your code
hub / github.com/Genaker/magento_gridjs

github.com/Genaker/magento_gridjs @5.1.11

Chat with this repo
repository ↗ · DeepWiki ↗ · release 5.1.11 ↗ · + Follow
388 symbols 959 edges 29 files 179 documented · 46%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Mage Grid Module

A powerful and flexible grid system for Magento 2 that provides an easy way to create and manage data grids in the admin panel.

Features

  • Flexible Data Sources: Support for both collection-based and SQL-based data sources
  • AJAX Support: Built-in AJAX functionality for smooth data loading
  • Customizable Fields: Easy field configuration and management
  • Built-in Filtering: Advanced filtering capabilities
  • Pagination: Automatic pagination handling
  • Frontend & Backend Support: Works in both frontend and backend contexts
  • Responsive Design: Mobile-friendly grid layout
  • Customizable Templates: Easy to override and customize templates

Why Our Grid is Better Than Magento's Legacy Grid

Our grid implementation offers several advantages over Magento's legacy grid system:

  1. Modern Technology Stack:
  2. Uses GridJS, a modern JavaScript grid library
  3. Built with Preact for efficient rendering
  4. Supports modern JavaScript features and async/await

  5. Better Performance:

  6. Lighter weight than Magento's legacy grid
  7. Faster rendering and data loading
  8. Reduced server load with client-side processing

  9. Enhanced Flexibility:

  10. Easy to customize columns and cells
  11. Support for both collection and SQL-based data sources
  12. Simple integration with Magento's UI components

  13. Improved Developer Experience:

  14. Cleaner code structure
  15. Better separation of concerns
  16. Easier to extend and maintain

  17. Better User Experience:

  18. Smoother interactions
  19. More responsive interface
  20. Better mobile support

  21. Advanced Features:

  22. Built-in AJAX support
  23. Advanced filtering capabilities
  24. Custom cell renderers
  25. Dynamic data loading

  26. Integration with Magento:

  27. Seamless integration with Magento's admin panel
  28. Support for Magento's UI components
  29. Compatible with Magento's theming system

Why This Grid is AI-First

Mage Grid is designed from the ground up to be AI-first. This means:

  • The codebase is structured for easy understanding and modification by AI coding assistants (like Cursor, GitHub Copilot, or ChatGPT).
  • Naming conventions, modularity, and documentation are optimized for AI-driven code generation and extension.
  • The grid is built to be easily extensible and customizable with minimal manual intervention, making it ideal for rapid prototyping and iterative development with AI tools.
  • Simple strait forward architecture and access to code with examples and documenttion makes it straightforward for LLMs to read, understand, and even improve your components. AI-Ready: Open code for LLMs to read, understand, and improve.

The design of the Mage Grids makes it easy for AI tools to work with your code. Its open code and simple API allow AI models to read, understand, and generate new components.

What Makes It AI-First?

  • Consistent, clear naming: Classes, methods, and templates are named for discoverability and semantic search.
  • Separation of concerns: Logic, templates, and configuration are cleanly separated, so AI can suggest or generate changes in isolation.
  • Extensive inline documentation: Comments and docblocks are written to help both humans and AI understand intent and usage.
  • Configurable via XML and DI: Most features (fields, processors, templates) are configured in XML or DI, so AI can suggest changes without deep PHP edits.
  • Composable processors: The data processor system is designed for easy extension and chaining, which is ideal for AI-driven code generation.
  • Template-driven UI: UI and JS are in templates, so AI can generate or modify UI logic without touching backend code.

How to Extend Mage Grid Using Cursor or AI

You can use AI tools like Cursor to: - Add new data processors (e.g., for custom formatting, badges, or links) - Add or modify grid fields and templates - Inject new JS/HTML for popups, modals, or custom actions - Refactor or optimize code for performance or maintainability

Example: Adding a Custom Data Processor with Cursor

  1. Describe your goal in Cursor:
  2. "Add a processor that renders the 'priority' field as a colored badge."
  3. Let Cursor search for DataProcessorInterface and StatusProcessor.
  4. Cursor generates a new PriorityProcessor.php:
  5. Implements the interface, adds color logic, and registers in di.xml.
  6. Update your layout XML to map the 'priority' field to the new processor.

Example: Adding a Popup with AI

  1. Describe your goal:
  2. "Add a popup that shows full row details when the 'Order Number' cell is clicked."
  3. AI suggests a new JS function and a template snippet.
  4. Add the JS to an additional-html.phtml template and configure it in layout XML.
  5. AI updates the grid template to include the new popup logic.

Practical Steps for AI-Driven Extension

  • Use Cursor's semantic search to find relevant classes, templates, or config files.
  • Use inline comments and docblocks to guide AI suggestions.
  • Use the modular template and processor system to add or override features without deep code changes.
  • Test changes iteratively, letting AI suggest fixes or improvements.

Tip: - The more you describe your intent (in comments, commit messages, or AI prompts), the better the AI can help you extend or refactor the grid.

AI Assistant Integration

The Mage Grid module includes an advanced AI Assistant that helps users interact with the grid using natural language queries. The AI Assistant:

  • Natural Language Filtering: Users can type queries in natural language (e.g., "show orders from last week", "find orders with status pending") and the AI will convert them into appropriate filters.
  • Terminal-like Interface: When users type "select" or similar SQL-like keywords, the input field transforms into a terminal-like interface with green text on black background and a blinking cursor.
  • Smart Suggestions: Provides alternative filter suggestions when the query is ambiguous or when multiple filtering options are available.
  • Context-Aware: Takes into account current filters, pagination, and sorting when suggesting new filters.
  • Error Handling: Gracefully handles unclear queries and asks for clarification when needed.
  • Performance Optimized: Caches frequent queries and optimizes filter combinations for better performance.

Installation

  1. Copy the module to your Magento installation:
cp -r app/code/Mage/Grid /path/to/magento/app/code/
  1. Enable the module:
bin/magento module:enable Mage_Grid
  1. Run setup upgrade:
bin/magento setup:upgrade
  1. Clear cache:
bin/magento cache:clean

Usage

Basic Grid Setup

  1. Create a layout file (e.g., view/adminhtml/layout/your_module_grid_index.xml):
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Mage\Grid\Block\MageGridBlock" name="your_grid">
                <arguments>
                    <argument name="viewModel" xsi:type="object">Mage\Grid\ViewModel\GenericViewModelGrid</argument>
                    <argument name="collectionClass" xsi:type="string">Your\Module\Model\ResourceModel\YourCollection</argument>
                    <argument name="fields" xsi:type="array">
                        <item name="id" xsi:type="string">ID</item>
                        <item name="name" xsi:type="string">Name</item>
                        <item name="created_at" xsi:type="string">Created At</item>
                    </argument>
                </arguments>
            </block>
        </referenceContainer>
    </body>
</page>
  1. Create a controller (e.g., Controller/Adminhtml/YourGrid/Index.php):
<?php
namespace Your\Module\Controller\Adminhtml\YourGrid;

use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;

class Index extends Action
{
    protected $resultPageFactory;

    public function __construct(
        Action\Context $context,
        PageFactory $resultPageFactory
    ) {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
    }

    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('Your_Module::your_grid');
    }

    public function execute()
    {
        $resultPage = $this->resultPageFactory->create();
        $resultPage->setActiveMenu('Your_Module::your_grid');
        $resultPage->getConfig()->getTitle()->prepend(__('Your Grid Title'));
        return $resultPage;
    }
}

Custom Column Cells with Preact

The module uses GridJS with Preact for rendering custom column cells. Here's how to create custom column cells:

  1. Basic Custom Column:
require(['jquery', 'gridjs'], function($, grid) {
    jQuery("#yourGrid").Grid({
        columns: [
            'Name',
            'Email',
            {
                name: 'Actions',
                formatter: (_, row) => html`<button onclick="editItem(${row.cells[0].data})">Edit</button>`
            }
        ],
        data: [
            ['John Doe', 'john@example.com'],
            ['Jane Smith', 'jane@example.com']
        ]
    });
});
  1. Complex Custom Column with Magento Integration:
require(['jquery', 'gridjs'], function($, grid) {
    jQuery("#yourGrid").Grid({
        columns: [
            'Order ID',
            'Customer',
            {
                name: 'Status',
                formatter: (cell, row) => {
                    const status = cell;
                    const color = status === 'Complete' ? 'green' : 'red';
                    return html`<span style="color: ${color}">${status}</span>`;
                }
            },
            {
                name: 'Actions',
                formatter: (_, row) => {
                    const orderId = row.cells[0].data;
                    return html`



                            <button onclick="viewOrder('${orderId}')">View</button>
                            <button onclick="editOrder('${orderId}')">Edit</button>
                            <button onclick="deleteOrder('${orderId}')">Delete</button>



                    `;
                }
            }
        ],
        data: [
            ['10001', 'John Doe', 'Complete'],
            ['10002', 'Jane Smith', 'Pending']
        ]
    });
});
  1. Custom Column with AJAX Data:
require(['jquery', 'gridjs'], function($, grid) {
    jQuery("#yourGrid").Grid({
        columns: [
            'Order ID',
            {
                name: 'Customer Details',
                formatter: async (_, row) => {
                    const orderId = row.cells[0].data;
                    const response = await fetch(`/rest/V1/orders/${orderId}`);
                    const data = await response.json();
                    return html`



                            <strong>${data.customer_firstname} ${data.customer_lastname}</strong>



                            <small>${data.customer_email}</small>



                    `;
                }
            }
        ],
        data: [
            ['10001'],
            ['10002']
        ]
    });
});
  1. Custom Column with Magento UI Components:
require(['jquery', 'gridjs', 'Magento_Ui/js/modal/alert'], function($, grid, alert) {
    jQuery("#yourGrid").Grid({
        columns: [
            'Order ID',
            {
                name: 'Actions',
                formatter: (_, row) => {
                    const orderId = row.cells[0].data;
                    return html`



                            <button onclick="showOrderDetails('${orderId}')">Details</button>



                    `;
                }
            }
        ],
        data: [
            ['10001'],
            ['10002']
        ]
    });

    window.showOrderDetails = function(orderId) {
        alert({
            title: 'Order Details',
            content: `Loading order ${orderId}...`,
            actions: {
                always: function() {
                    // Load order details via AJAX
                }
            }
        });
    };
});
  1. Custom Column with Magento Form Elements:
require(['jquery', 'gridjs'], function($, grid) {
    jQuery("#yourGrid").Grid({
        columns: [
            'Order ID',
            {
                name: 'Status',
                formatter: (cell, row) => {
                    const orderId = row.cells[0].data;
                    return html`
                        <select onchange="updateStatus('${orderId}', this.value)">
                            <option value="pending" ${cell === 'pending' ? 'selected' : ''}>Pending</option>
                            <option value="processing" ${cell === 'processing' ? 'selected' : ''}>Processing</option>
                            <option value="complete" ${cell === 'complete' ? 'selected' : ''}>Complete</option>
                        </select>
                    `;
                }
            }
        ],
        data: [
            ['10001', 'pending'],
            ['10002', 'processing']
        ]
    });
});

Configuration Options

The grid supports various configuration options:

  1. Collection-based Grid:
<argument name="collectionClass" xsi:type="string">Your\Module\Model\ResourceModel\YourCollection</argument>
  1. SQL-based Grid:
<argument name="tableName" xsi:type="string">your_table_name</argument>
  1. **F

Extension points exported contracts — how you extend this code

GridDataInterface (Interface)
* Interface for retrieving grid data */
Api/GridDataInterface.php
GridDataInterface (Interface)
* Interface for grid data response */
Api/Data/GridDataInterface.php
DataSourceInterface (Interface)
(no doc)
Model/Fields/DataSourceInterface.php
DataProcessorInterface (Interface)
(no doc)
Api/DataProcessorInterface.php
GridInterface (Interface)
* Interface GridInterface * @package Mage\Grid\Api\Data */
Api/Data/GridInterface.php

Core symbols most depended-on inside this repo

$
called by 162
view/adminhtml/web/js/preact.js
b
called by 66
view/adminhtml/web/js/gridjs.js
o
called by 45
view/adminhtml/web/js/gridjs.js
i
called by 42
view/adminhtml/web/js/gridjs.js
nt
called by 34
view/adminhtml/web/js/gridjs.js
_fnCallbackFire
called by 32
view/adminhtml/web/js/DataTable.js
rt
called by 25
view/adminhtml/web/js/gridjs.js
getData
called by 14
Model/Grid.php

Shape

Function 254
Method 110
Class 19
Interface 5

Languages

TypeScript65%
PHP35%

Modules by API surface

view/adminhtml/web/js/DataTable.js165 symbols
view/adminhtml/web/js/preact.js45 symbols
view/adminhtml/web/js/gridjs.js44 symbols
ViewModel/GenericViewModelGrid.php28 symbols
Model/Grid.php15 symbols
Block/GenericGrid.php15 symbols
Controller/Adminhtml/Grid/Filter.php10 symbols
Model/Fields/DefaultDataSource.php7 symbols
Model/Fields/DataSourceInterface.php5 symbols
Model/DataProcessor/ChainProcessor.php5 symbols
Block/Grid/Filters.php5 symbols
Model/DataProcessor/DefaultProcessor.php4 symbols

For agents

$ claude mcp add magento_gridjs \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact