Troubleshooter
Troubleshooter

Reputation: 101

Magento 2 grid structure

I have started looking into Magento 2 grid. I have developed one simple module but I didn't understand the structure of grid.

In Magento 1.9.X, the way was clear for adding grid but in Magento 2 there is structure is different. How do I add a grid in Magento 2?

Upvotes: 0

Views: 2826

Answers (4)

Abhinay
Abhinay

Reputation: 61

1:Create controller Index.php

 <?php

 namespace Ced\Abhinay\Controller\Adminhtml\Account;

 class Index extends \Magento\Backend\App\Action {

 /**
 * @var bool|\Magento\Framework\View\Result\PageFactory
 */
 protected $resultPageFactory = false;

 /**
 * Index constructor.
 * @param \Magento\Backend\App\Action\Context $context
 * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
 */

 public function __construct(
    \Magento\Backend\App\Action\Context $context,
    \Magento\Framework\View\Result\PageFactory $resultPageFactory
 )
 {
    parent::__construct($context);
    $this->resultPageFactory = $resultPageFactory;
 }

 public function execute()
 {
    $resultPage = $this->resultPageFactory->create();
    $resultPage->getConfig()->getTitle()->prepend((__('Ced Abhinay')));

    return $resultPage;
 }

 }

2:After that create layout file for this

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-          2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
    <referenceContainer name="content">
        <block class="Ced\Abhinay\Block\Adminhtml\Account\ListGrid" name="ced_custom_grid"/>
    </referenceContainer>
</body>
</page>

3.After that create file ListGrid.php

<?php
  namespace Ced\Abhinay\Block\Adminhtml\Account;

  class ListGrid extends \Magento\Backend\Block\Widget\Grid\Container {

  /**
  * Class ListGrid extends parent constructor \Magento\Backend\Block     \Widget\Grid
 */
 protected function _construct()
 {
    $this->_controller = 'account_index';
    $this->_blockGroup = 'Ced_Abhinay';
    $this->_addButtonLabel = __('Ced Test');
    parent::_construct();
 }
 }

4:Now finally create your Grid.php

<?php

namespace Ced\Abhinay\Block\Adminhtml\Account\Grid;

class Grid extends \Magento\Backend\Block\Widget\Grid\Extended {

/** @var \Ced\Abhinay\Model\ListModel */
protected $listModelData;

/**
 * Grid constructor.
 * @param \Magento\Backend\Block\Template\Context $context
 * @param \Magento\Backend\Helper\Data $backendHelper
 * @param \Ced\Abhinay\Model\ListModel $listModelData
 * @param array $data
 */

public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    \Magento\Backend\Helper\Data $backendHelper,
    \Ced\Abhinay\Model\ListModel $listModelData,
    array $data = []
) {
    parent::__construct($context, $backendHelper, $data);
    $this->listModelData = $listModelData;
}

protected function _construct()
{
    parent::_construct();
    $this->setId('list_grid');
    $this->setDefaultSort('list_id');
    $this->setDefaultDir('DESC');
    $this->isAjax('true');
}

protected function _prepareCollection()
{
    $collection = $this->listModelData->getCollection();
    $this->setCollection($collection);

    return parent::_prepareCollection();
}

protected function _prepareColumns()
{
    $this->addColumn(
        'post_id',
        [
            'header' => __('ID'),
            'sortable' => true,
            'index' => 'post_id',
            'type' => 'number',
            'header_css_class' => 'col-id',
            'column_css_class' => 'col-id'
        ]
    );
    $this->addColumn(
        'title',
        [
            'header' => __('Name'),
            'index' => 'name',
            'header_css_class' => 'col-name',
            'column_css_class' => 'col-name'
        ]
    );
    $this->addColumn(
        'position',
        [
            'header' => __('Position'),
            'name' => 'position',
            'width' => 60,
            'type' => 'number',
            'validate_class' => 'validate-number',
            'index' => 'position',
            'editable' => true,
        ]
    );

    return parent::_prepareColumns();
}
}

Upvotes: 1

DanijelDjuric
DanijelDjuric

Reputation: 1

Now the preferred way of adding grid inside adminhtml is with ui components

Reason why it's the best way now is because you can use a lot of magento 2 backend functionality when adding it as ui component.

However there are multiple ways to add this. Not to repeat the answer and tons of code in stackoverflow i found a mageplaza explination, that explains the creation of the grid.

https://www.mageplaza.com/magento-2-module-development/create-admin-grid-magento-2.html

You can also refer to magento 2 documentation to take a look on additional components you can use in you ui component:

https://devdocs.magento.com/guides/v2.0/ui-components/ui-component.html

There are multiple existing components you can you in grid and you can create your own. Aldo complex they do offer big amount of flexibility when setuped. And when you do create a couple you will understand how they function and will be able to work with them with ease.

Upvotes: 0

szumel
szumel

Reputation: 105

The best practice is to create all grids via UI components (xml).

Look into Magento_Catalog module and find product_form.xml.

Upvotes: 0

Nicolas
Nicolas

Reputation: 66

In Magento 2, you can create a grid by XML (see here)

However, you can create a grid by PHP like Magento 1: Extending your grid class to "Magento\Backend\Block\Widget\Grid\Extended"

<?php

namespace Yourpackage\Yourmodule\Block\Adminhtml\Sample;

class Grid extends \Magento\Backend\Block\Widget\Grid\Extended
{
    protected $_yourmodelFactory;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Backend\Helper\Data $backendHelper,
        \Yourpackage\Yourmodule\Model\YourmodelFactory $yourmodelFactory,
        array $data = []
    ) {
        parent::__construct($context, $backendHelper, $data);
        $this->_yourmodelFactory = $yourmodelFactory;
    }

    protected function _construct()
    {
        parent::_construct();
        $this->setId('sample_grid');
        $this->setDefaultSort('id');
        $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
    }

    protected function _prepareCollection()
    {
        $collection = $this->_yourmodelFactory->create()->getCollection();
        $this->setCollection($collection);

        return parent::_prepareCollection();
    }

    protected function _prepareColumns()
    {
        $this->addColumn(
            'id',
            [
                'header' => __('ID'),
                'align'  => 'right',
                'width'  => '50px',
                'index'  => 'id',
            ]
        );

        // Some columns

        return parent::_prepareColumns();
    }
}

You can see more at: /vendor/magento/module-cms/Block/Adminhtml/Page/Grid.php.

Upvotes: 4

Related Questions