Ngoài cách sử dụng Ui component, bạn còn có thể sử dụng block để tạo grid trong Magento 2.
Xem thêm: Tạo grid trong Magento 2 với UiComponent
1. Tạo layout
Trong layout xml file hãy thêm đoạn code sau:
1 2 3 4 5 6 7 8 9 10 |
<?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="ViMagento\HelloWorld\Block\Adminhtml\Post" name="post.block"> <block class="ViMagento\HelloWorld\Block\Adminhtml\Post\Grid" name="post.grid" /> </block> </referenceContainer> </body> </page> |
ViMagento\HelloWorld\Block\Adminhtml\Post
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php namespace ViMagento\HelloWorld\Block\Adminhtml; /** * Class Post * @package ViMagento\HelloWorld\Block\Adminhtml */ class Post extends \Magento\Backend\Block\Widget\Grid\Container { protected function _construct() { $this->_blockGroup = 'ViMagento_HelloWorld'; $this->_controller = 'adminhtml_post'; parent::_construct(); } } |
2. Tạo grid
ViMagento\HelloWorld\Block\Adminhtml\Post\Grid
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
<?php namespace ViMagento\HelloWorld\Block\Adminhtml\Post; /** * Class Grid * @package ViMagento\HelloWorld\Block\Adminhtml\Post */ class Grid extends \Magento\Backend\Block\Widget\Grid\Extended { /** * @var \ViMagento\HelloWorld\Model\ResourceModel\Post\CollectionFactory */ protected $postCollection; /** * Grid constructor. * @param \Magento\Backend\Block\Template\Context $context * @param \Magento\Backend\Helper\Data $backendHelper * @param \ViMagento\HelloWorld\Model\ResourceModel\Post\CollectionFactory $collectionFactory * @param array $data */ public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Backend\Helper\Data $backendHelper, \ViMagento\HelloWorld\Model\ResourceModel\Post\CollectionFactory $collectionFactory, array $data = [] ) { $this->postCollection = $collectionFactory; parent::__construct($context, $backendHelper, $data); } protected function _prepareCollection() { $this->setCollection($this->postCollection->create()); return parent::_prepareCollection(); } /** * Prepare grid columns * * @return $this * @throws \Exception */ protected function _prepareColumns() { $this->addColumn( 'post_id', ['header' => __('ID'), 'index' => 'post_id', ] ); $this->addColumn( 'name', [ 'header' => __('Name'), 'index' => 'name', ] ); $this->addColumn( 'status', [ 'header' => __('Status'), 'index' => 'status', 'type' => 'options', 'options' => [ 1 => __('Pending'), 2 => __('Publish') ], ] ); $this->addColumn( 'content', [ 'header' => __('Content'), 'index' => 'content', ] ); return $this; } } |
Kết quả:
