How can we create admin grid by using Block (.php) file? Everytime when I tried to create block via .php file, I got stuck in between and didn't find any solution.
This time I am successful in this.
So posting a question here with answer. Hope it helps you..!!
1 Answer 1
1) app/code/[Vendor_Name]/[Namespace]/registration.php :
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
 \Magento\Framework\Component\ComponentRegistrar::MODULE,
 '[Vendor_Name]_[Namespace]',
 __DIR__
);
2) app/code/[Vendor_Name]/[Namespace]/etc/module.xml :
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
 <module name="[Vendor_Name]_[Namespace]" setup_version="1.0.0" />
</config>
3) app/code/[Vendor_Name]/[Namespace]/etc/adminhtml/routes.xml :
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
 <router id="admin">
 <route id="[myurl]" frontName="[myurl]">
 <module name="[Vendor_Name]_[Namespace]" />
 </route>
 </router>
</config>
4) app/code/[Vendor_Name]/[Namespace]/etc/adminhtml/menu.xml :
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">
 <menu>
 <add id="[Vendor_Name]_[Namespace]::myadmingrid" title="My admin grid" module="[Vendor_Name]_[Namespace]" sortOrder="50" parent="Magento_Sales::sales" action="[myurl]/index/index" resource="[Vendor_Name]_[Namespace]::myadmingrid"/>
 </menu>
</config>
5) app/code/[Vendor_Name]/[Namespace]/view/adminhtml/layout/[myurl]_index_index.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_Name]\[Namespace]\Block\Adminhtml\MyGrid" name="my_admin_grid"/>
 </referenceContainer>
 <referenceContainer name="admin.myadmingrid.grid"></referenceContainer>
 </body>
</page>
6) app/code/[Vendor_Name]/[Namespace]/view/adminhtml/templates/grid.phtml :
<?php echo $block->getGridHtml() ?>
7) app/code/[Vendor_Name]/[Namespace]/Controller/Adminhtml/Index/Index.php :
<?php
 namespace [Vendor_Name]\[Namespace]\Controller\Adminhtml\Index;
 use Magento\Backend\App\Action;
 class Index extends \Magento\Backend\App\Action{
 /**
 * @var \Magento\Framework\View\Result\PageFactory
 */
 private $resultPageFactory;
 /**
 * @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->setActiveMenu('[Vendor_Name]_[Namespace]::myadmingrid');
 $resultPage->getConfig()->getTitle()->prepend(__('My Admin Grid'));
 return $resultPage;
 }
 }
8) app/code/[Vendor_Name]/[Namespace]/Block/Adminhtml/MyGrid.php :
<?php
namespace [Vendor_Name]\[Namespace]\Block\Adminhtml;
class MyGrid extends \Magento\Backend\Block\Widget\Container
{
 /**
 * @var string
 */
 protected $_template = 'grid.phtml';
 /**
 * @param \Magento\Backend\Block\Widget\Context $context
 * @param array $data
 */
 public function __construct(\Magento\Backend\Block\Widget\Context $context,array $data = [])
 {
 parent::__construct($context, $data);
 }
 /**
 * Prepare button and grid
 *
 * @return \Magento\Catalog\Block\Adminhtml\Product
 */
 protected function _prepareLayout()
 {
 $this->setChild(
 'grid',
 $this->getLayout()->createBlock('[Vendor_Name]\[Namespace]\Block\Adminhtml\MyGrid\Grid', 'admin.myadmingrid.grid')
 );
 return parent::_prepareLayout();
 }
 /**
 * Render grid
 *
 * @return string
 */
 public function getGridHtml()
 {
 return $this->getChildHtml('grid');
 }
}
9) app/code/[Vendor_Name]/[Namespace]/Block/Adminhtml/MyGrid/Grid.php :
<?php
namespace [Vendor_Name]\[Namespace]\Block\Adminhtml\MyGrid;
class Grid extends \Magento\Backend\Block\Widget\Grid\Extended
{
 /**
 * @var \Magento\Framework\Module\Manager
 */
 protected $moduleManager;
 protected $itemFactory;
 /**
 * @param \Magento\Backend\Block\Template\Context $context
 * @param \Magento\Backend\Helper\Data $backendHelper
 * @param \Magento\Framework\Module\Manager $moduleManager
 * @param array $data
 *
 * @SuppressWarnings(PHPMD.ExcessiveParameterList)
 */
 public function __construct(
 \Magento\Backend\Block\Template\Context $context,
 \Magento\Backend\Helper\Data $backendHelper,
 \Magento\Sales\Model\Order\ItemFactory $itemFactory,
 \Magento\Framework\Module\Manager $moduleManager,
 array $data = []
 ) {
 $this->itemFactory = $itemFactory;
 $this->moduleManager = $moduleManager;
 parent::__construct($context, $backendHelper, $data);
 }
 /**
 * @return void
 */
 protected function _construct()
 {
 parent::_construct();
 $this->setId('postGrid');
 $this->setDefaultSort('created_at');
 $this->setDefaultDir('DESC');
 $this->setSaveParametersInSession(true);
 $this->setUseAjax(false);
 $this->setVarNameFilter('post_filter');
 }
 /**
 * @return $this
 */
 protected function _prepareCollection()
 {
 //You can select your custom data here
 $collection = $this->itemFactory->create()->getCollection();
 $collection->getSelect()
 ->join(array('sales_order'), 'main_table.order_id= sales_order.entity_id',array('orderstatus' => 'sales_order.status', 'customer_id' => 'sales_order.customer_id', 'increment_id' => 'sales_order.increment_id'))
 ->join(array('customer_entity'), 'sales_order.customer_id= customer_entity.entity_id',array('firstname' => 'customer_entity.firstname', 'lastname' => 'customer_entity.lastname'))
 ->join(array('store'), 'main_table.store_id= store.store_id',array('store' => 'store.name'))
 ->where('order_item_serialcode.status=1');
 $collection->addExpressionFieldToSelect(
 'fullname',
 'CONCAT({{customer_firstname}}, \' \', {{customer_lastname}})',
 array('customer_firstname' => 'firstname', 
 'customer_lastname' => 'lastname')
 );
 $this->setCollection($collection);
 parent::_prepareCollection();
 return $this;
 }
 /**
 * @return $this
 * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
 */
 protected function _prepareColumns()
 {
 $this->addColumn(
 'store',
 [
 'header' => __('Store'),
 'index' => 'store',
 ]
 );
 $this->addColumn(
 'fullname',
 [
 'header' => __('Customer'),
 'index' => 'fullname',
 ]
 );
 // If you want to export data
 $this->addExportType($this->getUrl('[myurl]/index/exportCsv', ['_current' => true]),__('CSV'));
 $this->addExportType($this->getUrl('[myurl]/index/exportExcel', ['_current' => true]),__('Excel XML'));
 $block = $this->getLayout()->getBlock('grid.bottom.links');
 if ($block) {
 $this->setChild('grid.bottom.links', $block);
 }
 return parent::_prepareColumns();
 }
 
 /**
 * @return string
 */
 public function getGridUrl()
 {
 return $this->getUrl('[myurl]/index/index', ['_current' => true]);
 }
 public function getRowUrl($row)
 {
 return '#';
 } 
}
10) app/code/[Vendor_Name]/[Namespace]/view/adminhtml/layouot/[myurl]_index_exportcsv.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">
 <update handle="[myurl]_index_grid"/>
</page>
11) app/code/[Vendor_Name]/[Namespace]/view/adminhtml/layouot/[myurl]_index_exportexcel.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">
 <update handle="[myurl]_index_grid"/>
</page>
12) app/code/[Vendor_Name]/[Namespace]/Controller/Adminhtml/Index/ExportCsv.php :
<?php
namespace [Vendor_Name]\[Namespace]\Controller\Adminhtml\Index;
use Magento\Backend\App\Action;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\Response\Http\FileFactory;
class ExportCsv extends \Magento\Backend\App\Action
{
 protected $_fileFactory;
 public function execute()
 {
 $this->_view->loadLayout(false);
 $fileName = 'mygridreport.csv';
 $exportBlock = $this->_view->getLayout()->createBlock('[Vendor_Name]\[Namespace]\Block\Adminhtml\Report\Grid');
 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 $this->_fileFactory = $objectManager->create('Magento\Framework\App\Response\Http\FileFactory');
 return $this->_fileFactory->create(
 $fileName,
 $exportBlock->getCsvFile(),
 DirectoryList::VAR_DIR
 );
 }
}
12) app/code/[Vendor_Name]/[Namespace]/Controller/Adminhtml/Index/ExportExcel.php :
<?php
namespace [Vendor_Name]\[Namespace]\Controller\Adminhtml\Report;
use Magento\Backend\App\Action;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\Response\Http\FileFactory;
class ExportExcel extends \Magento\Backend\App\Action
{
 protected $_fileFactory;
 public function execute()
 {
 $this->_view->loadLayout(false);
 $fileName = 'mygridexport.xml';
 $exportBlock = $this->_view->getLayout()->createBlock('[Vendor_Name]\[Namespace]\Block\Adminhtml\Report\Grid');
 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 $this->_fileFactory = $objectManager->create('Magento\Framework\App\Response\Http\FileFactory');
 return $this->_fileFactory->create(
 $fileName,
 $exportBlock->getExcelFile(),
 DirectoryList::VAR_DIR
 );
 }
}