Magento 2

CREATE A GRID IN BACKEND ADMIN MAGENTO 2

In magento 1x, it is so easy to create a grid show data in backend and magento 2 is so similar. Only with some part you can create a grid to show data from a table easily. However magento 2 gives you two ways to create a grid in backend. Today I will help you create a grid with simple way, so similar with magento 1x.

This is an example: customer grid

grid

We will use extension: Magenhub_Chris to create a grid similar with this grid. This extension contained code create table, model, resource model and collection so when using it, we don’t need to create them again.

1. Create a custom menu in backend

In the lesson create new configuration in magento 2, I help you create a menu Settings in Magento 2 backend and now you can do similar to create new submenu with name Item Manager before Settings menu.

menu

File: app\code\Magenhub\Chris\etc\adminhtml\menu.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../Backend/etc/menu.xsd">
 <menu>
 <add id="Magenhub_Chris::chris" title="Chris Module" module="Magenhub_Chris" sortOrder="10" resource="Magenhub_Chris::chris"/>
 <add id="Magenhub_Chris::items" title="Item manager" module="Magenhub_Chris" sortOrder="15" parent="Magenhub_Chris::chris" action="chrisadmin/chris/index" resource="Magenhub_Chris::items"/>
 <add id="Magenhub_Chris::settings" title="Settings" module="Magenhub_Chris" sortOrder="20" parent="Magenhub_Chris::chris" action="adminhtml/system_config/edit/section/chris" resource="Magenhub_Chris::settings"/>
 </menu>
</config>

You can see the action we point to is chrisadmin/chris/index so the next step is creating a controller.

2. Create file controller

Path: app\code\Magenhub\Chris\Controller\Adminhtml\Chris\Index.php

namespace Magenhub\Chris\Controller\Adminhtml\Chris;
class Index extends \Magento\Backend\App\Action {

 /**
 * @var \Magento\Framework\View\Result\PageFactory
 */
 protected $resultPageFactory;

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

 public function execute() {
     if ($this->getRequest()->getQuery('ajax')) {
     $this->_forward('grid');
     return;
     }
     $resultPage = $this->resultPageFactory->create();
     $this->_view->loadLayout();
     $this->_setActiveMenu('Magenhub_Chris::items');
     $this->_addBreadcrumb(__('Item Manager'), __('Item Manager'));
     $resultPage->getConfig()->getTitle()->prepend(__('Item Manager'));
     $this->_view->renderLayout();
 }
}

Please see a lot of important information:

  • \Magento\Backend\App\Action: almost action for backend extends from this class
  • Magenhub_Chris::items: this is the id of menu that we declare in menu.xml file

3. Create file layout

In controller file we used 2 functions are: loadLayout and renderLayout for object $this->_view so we need to create a layout file to call blocks.

<?xml version="1.0" encoding="UTF-8"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
 <update handle="chrisadmin_index_grid_block"/>
 <body>
 <referenceContainer name="content">
 <block class="Magenhub\Chris\Block\Adminhtml\Chris" name="chrisblock"/>
 </referenceContainer>
 </body>
</page>

In this file we called block: Magenhub\Chris\Block\Adminhtml\Chris

Please go to next part to know how to create it.

4. Create file block grid

* Block file: app\code\Magenhub\Chris\Block\adminhtml\Chris.php

namespace Magenhub\Chris\Block\Adminhtml;
class Chris extends \Magento\Backend\Block\Widget\Grid\Container {
     /**
     * Constructor
     *
     * @return void
     */
     protected function _construct() {
         $this->_controller = 'adminhtml_chris';
         $this->_blockGroup = 'Magenhub_Chris';
         $this->_headerText = __('Item Manager');
         $this->_addButtonLabel = __('Add Item');
         parent::_construct();
     }
}

There are some information is so important:

+ $this->_controller: the path to block

block

+ $this->_blockGroup: the path of module

blockgroup

* Block grid file: app\code\Magenhub\Chris\Block\Adminhtml\Chris\Grid.php


namespace Magenhub\Chris\Block\Adminhtml\Chris;

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

    /**
    * banner factory
    * @var \Magenhub\Chris\Model\ChrisFactory
    */
    protected $_chrisFactory;

    /**
    * Registry object
    * @var \Magento\Framework\Registry
    */
    protected $_coreRegistry;

    /**
    * [__construct description]
    * @param \Magento\Backend\Block\Template\Context $context [description]
    * @param \Magento\Backend\Helper\Data $backendHelper [description]
    * @param \Magenhub\Chris\Model\ChrisFactory $chrisFactory [description]
    * @param \Magento\Framework\Registry $coreRegistry [description]
    * @param array $data [description]
    */
    public function __construct(
    \Magento\Backend\Block\Template\Context $context, \Magento\Backend\Helper\Data $backendHelper, \Magenhub\Chris\Model\ChrisFactory $chrisFactory, \Magento\Framework\Registry $coreRegistry, array $data = []
    ) {
        $this->_chrisFactory = $chrisFactory;
        $this->_coreRegistry = $coreRegistry;
        parent::__construct($context, $backendHelper, $data);
    }

    protected function _construct() {
        parent::_construct();
        $this->setId('chrisGrid');
        $this->setDefaultSort('chris_id');
        $this->setDefaultDir('ASC');
        $this->setSaveParametersInSession(true);
        $this->setUseAjax(true);
    }

    protected function _prepareCollection() {
        $collection = $this->_chrisFactory->create()->getCollection();
        $this->setCollection($collection);
        return parent::_prepareCollection();
    }

    /**
    * @return $this
    */
    protected function _prepareColumns() {
        $this->addColumn(
        'chris_id', [
        'header' => __('Chris ID'),
        'type' => 'number',
        'index' => 'chris_id',
        'header_css_class' => 'col-id',
        'column_css_class' => 'col-id',
        'width' => '30px',
        ]
        );
        $this->addColumn(
        'name', [
        'header' => __('Name'),
        'index' => 'name',
        'class' => 'xxx',
        'width' => '50px',
        ]
        );
        $this->addColumn(
        'email', [
        'header' => __('Email'),
        'class' => 'xxx',
        'width' => '100px',
        'index' => 'email'
        ]
        );
        $this->addColumn(
        'created_at', [
        'header' => __('Created time'),
        'type' => 'datetime',
        'index' => 'created',
        'class' => 'xxx',
        'width' => '50px',
        ]
        );
        $status = $statuses = ['1' => __('Enable'), '2' => __('Disable')];
        $this->addColumn(
        'status', [
        'header' => __('Status'),
        'index' => 'status',
        'type' => 'options',
        'options' => $status,
        ]
        );
        $this->addColumn(
        'edit', [
        'header' => __('Edit'),
        'type' => 'action',
        'getter' => 'getId',
        'actions' => [
        [
        'caption' => __('Edit'),
        'url' => ['base' => '*/*/edit'],
        'field' => 'chris_id',
        ],
        ],
        'filter' => false,
        'sortable' => false,
        'index' => 'stores',
        'header_css_class' => 'col-action',
        'column_css_class' => 'col-action',
        ]
        );
        $this->addExportType('*/*/exportCsv', __('CSV'));
        $this->addExportType('*/*/exportXml', __('XML'));
        $this->addExportType('*/*/exportExcel', __('Excel'));

        return parent::_prepareColumns();
    }

    /**
    * @return $this
    */
    protected function _prepareMassaction() {
        $this->setMassactionIdField('chris_id');
        $this->getMassactionBlock()->setFormFieldName('chris');

        $this->getMassactionBlock()->addItem(
        'delete', [
        'label' => __('Delete'),
        'url' => $this->getUrl('chrisadmin/*/massDelete'),
        'confirm' => __('Are you sure?'),
        ]
        );

        $statuses = ['1' => __('Enable'), '2' => __('Disable')];

        array_unshift($statuses, ['label' => '', 'value' => '']);
        $this->getMassactionBlock()->addItem(
        'status', [
        'label' => __('Change status'),
        'url' => $this->getUrl('bannerslideradmin/*/massStatus', ['_current' => true]),
        'additional' => [
        'visibility' => [
        'name' => 'status',
        'type' => 'select',
        'class' => 'required-entry',
        'label' => __('Status'),
        'values' => $statuses,
        ],
        ],
        ]
        );
        return $this;
    }

    /**
    * @return string
    */
    public function getGridUrl() {
        return $this->getUrl('*/*/grid', ['_current' => true]);
    }

    public function getRowUrl($row) {
        return $this->getUrl(
        '*/*/edit', ['chris_id' => $row->getId()]
        );
    }

}

This code is so long but so easy to understand because it is similar with magento 1x. After click into menu Item Manager you can see:

chrisgrid

And you can download code here to compare if you want. Thank you for reading!

 
 
 
 

0 Bình luận

Trở về
  • Magento plug-ins
  • Magento plug-ins

    Magento2 gave very good concept called Plugin   we can do what ever after and before core function and also we have...

  • HOW TO CREATE MENU IN MAGENTO 2 ADMIN
  • HOW TO CREATE MENU IN MAGENTO 2 ADMIN

    magento-2-admin- menu My previous tutorial show you how to create a simple module in Magento 2, learn more here: http://www.venustheme.com/how-to-create-magento-2-module/....