How to Create Admin Grid,edit/add in Magento 2

How to Create Admin Grid,edit/add in Magento 2

I’m sharing with you this post ,which guide you how to create admin grid,edit/add in Magento 2.I’m going to use Magento 2 Community Edition (CE) for this purpose.
If you are familiar with Magento 1 grid then it easy to understand Magento 2 Grid, which is table row listing patterns of your database table. Magento Grid provide you all kind of operations like: sort, filter, delete, update item, etc.
You can create below directory structure before start.We will need all those directory structure for create admin grid edit/add grid row and installer.

app/code/Ak/GridExample
app/code/Ak/GridExample/etc
app/code/Ak/GridExample/etc/Adminhtml
app/code/Ak/GridExample/Block/Adminhtml
app/code/Ak/GridExample/Block/Adminhtml/Grid
app/code/Ak/GridExample/Block/Adminhtml/Grid/Edit
app/code/Ak/GridExample/Model
app/code/Ak/GridExample/Model/ResourceModel
app/code/Ak/GridExample/Model/ResourceModel/Grid
app/code/Ak/GridExample/Setup
app/code/Ak/GridExample/Controllers/Adminhtml
app/code/Ak/GridExample/view/adminhtml/layout

 

Steps to Create Admin Grid

Step 1: Create Module Configuration File
Step 2: Create Module Registration File
Step 3: Create Composer File for Auto Install
Step 4: Create Menu Configuration File
Step 5: Create Database schema
Step 6: Create Model File
Step 7: Create Model Interface File
Step 9: Create Resource Model File
Step 10: Create Resource Collection File
Step 11: Create Admin Grid using Ui Component
Step 12: Create Map Data File & UI Action
Step 13: Create “Create”,Save,MassDelete etc. Action Files (Controller Files)
Step 14: Create Option status file
Step 15: Create Route File
Step 16: Create Grid Display Layout File
Step 17: Create Block File for Save/Edit Data process file
Step 18: Create Layout File for Render the Form

Step 1:  Create Module Configuration File

Create The Module Configuration File Named Module.Xml on below path.
Path: app/code/Ak/GridExample/etc

 

<?xml version="1.0"?>
<!--
/** GridExample module xml
 * @category  Ak
 * @package   Ak_GridExample
 * @author    Ak
 * @copyright Copyright (c) 2005-2017 Adesh Suryan (https://adeshsuryan.in)
 * @license   http://www.opensource.org/licenses/gpl-2.0.php
 */
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Ak_GridExample" setup_version="2.0.0">
    </module>
</config>

 

Step 2:  Create Module Registration File

Create The Module Registration File Named Registration.php on below path.
Path: app/code/Ak/GridExample/

 

<?php
/** GridExample Module registration
 * @category  Ak
 * @package   Ak_GridExample
 * @author    Ak
 * @copyright Copyright (c) 2005-2017 Adesh Suryan (https://adeshsuryan.in)
 * @license   http://www.opensource.org/licenses/gpl-2.0.php
 */
 
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Ak_GridExample',
    __DIR__
);

 

Step 3:  Create Composer File for Auto Install

Create The Module Composer File Named composer.json on below path.
Path: app/code/Ak/GridExample/

 

{
    "name": "ak/magento2-create-admin-grid",
    "description": "Composer create collection Grid , Edit/Add Grid Row 
                    and Installer in Magento2",
    "require": {
        "php": "~5.5.0|~5.6.0|~7.0.0"
    },
    "type": "magento2-module",
    "version": "2.0.0",
    "license": [
        "OSL-3.0",
        "AFL-3.0"
    ],
    "autoload": {
        "files": [
            "registration.php"
        ],
        "psr-4": {
            "Ak\\GridExample\\": ""
        }
    }
}

 

Step 4:  Create Menu Configuration File 

Create The admin menu configuration file named Menu.Xml on below path.
Path: app/code/Ak/GridExample/etc/Adminhtml

<?xml version="1.0"?>
<!--
/** GridExample Module registration
 * @category  Ak
 * @package   Ak_GridExample
 * @author    Ak
 * @copyright Copyright (c) 2005-2017 Adesh Suryan (https://adeshsuryan.in)
 * @license   http://www.opensource.org/licenses/gpl-2.0.php
 */
 */
-->

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">
  <menu>
  <add id="Ak_GridExample::manager" title="Grid Manager" module="Ak_GridExample" 
        sortOrder="10" resource="Ak_GridExample::manager" />
  <add id="Ak_GridExample::add_row" title="Grid Manager" module="Ak_GridExample"
  sortOrder="20" parent="Ak_GridExample::manager" action="gridexample/gridexample" 
         resource="Ak_GridExample::add_row"/>
  </menu>
</config>

 

Step 5:  Create Database schema 

Create The Installer file named InstallSchema.php on below path.
Path: app/code/Ak/GridExample/Setup

 

<?php
/** GridExample Schema Setup
 * @category  Ak
 * @package   Ak_GridExample
 * @author    Ak
 * @copyright Copyright (c) 2005-2017 Adesh Suryan (https://adeshsuryan.in)
 * @license   http://www.opensource.org/licenses/gpl-2.0.php
 */

namespace Ak\GridExample\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\App\Filesystem\DirectoryList;

/**
 * @codeCoverageIgnore
 */
class InstallSchema implements InstallSchemaInterface
{
    /**
     * {@inheritdoc}
     *
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(
        SchemaSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $installer = $setup;

        $installer->startSetup();

        /*
         * Create table 'ak_gridexample_records'
         */

        $table = $installer->getConnection()->newTable(
            $installer->getTable('ak_gridexample_records')
        )->addColumn(
            'entity_id',
            \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
            null,
            ['identity' => true, 'nullable' => false, 'primary' => true],
            'Grid Record Id'
        )->addColumn(
            'title',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            255,
            ['nullable' => false],
            'Title'
        )->addColumn(
            'content',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            255,
            ['nullable' => false],
            'Content'
        )->addColumn(
            'publish_date',
            \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
            null,
            [],
            'Publish Date'
        )->addColumn(
            'is_active',
            \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
            null,
            [],
            'Active Status'
        )->addColumn(
            'created_at',
            \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
            null,
            [
                'nullable' => false,
                'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT,
            ],
            'Creation Time'
        )->addColumn(
            'update_time',
            \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
            null,
            ['nullable' => false,
             'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE
            ],
            'Modification Time'
        )->setComment(
            'Row Data Table'
        );

        $installer->getConnection()->createTable($table);
        $installer->endSetup();
    }
}

 

Step 6:  Create Model File

Create The Model file named GridExample.php on below path.
Path: app/code/Ak/GridExample/Model

 

<?php
/** GridExample GridExample Model
 * @category  Ak
 * @package   Ak_GridExample
 * @author    Ak
 * @copyright Copyright (c) 2005-2017 Adesh Suryan (https://adeshsuryan.in)
 * @license   http://www.opensource.org/licenses/gpl-2.0.php
 */
  
namespace Ak\GridExample\Model;

use Ak\GridExample\Api\Data\GridInterface;
use Magento\Framework\Model\AbstractModel;

class GridExample extends AbstractModel implements GridInterface
{

    /**
     * Initialize resource model.
     */
    protected function _construct()
    {
        $this->_init(\Ak\GridExample\Model\ResourceModel\GridExample::class);
    }
    /**
     * Get EntityId.
     *
     * @return int
     */
    public function getEntityId()
    {
        return $this->getData(self::ENTITY_ID);
    }

    /**
     * Set EntityId.
     */
    public function setEntityId($entityId)
    {
        return $this->setData(self::ENTITY_ID, $entityId);
    }

    /**
     * Get Title.
     *
     * @return varchar
     */
    public function getTitle()
    {
        return $this->getData(self::TITLE);
    }

    /**
     * Set Title.
     */
    public function setTitle($title)
    {
        return $this->setData(self::TITLE, $title);
    }

    /**
     * Get getContent.
     *
     * @return varchar
     */
    public function getContent()
    {
        return $this->getData(self::CONTENT);
    }

    /**
     * Set Content.
     */
    public function setContent($content)
    {
        return $this->setData(self::CONTENT, $content);
    }

    /**
     * Get PublishDate.
     *
     * @return varchar
     */
    public function getPublishDate()
    {
        return $this->getData(self::PUBLISH_DATE);
    }

    /**
     * Set PublishDate.
     */
    public function setPublishDate($publishDate)
    {
        return $this->setData(self::PUBLISH_DATE, $publishDate);
    }

    /**
     * Get IsActive.
     *
     * @return varchar
     */
    public function getIsActive()
    {
        return $this->getData(self::IS_ACTIVE);
    }

    /**
     * Set IsActive.
     */
    public function setIsActive($isActive)
    {
        return $this->setData(self::IS_ACTIVE, $isActive);
    }

    /**
     * Get UpdateTime.
     *
     * @return varchar
     */
    public function getUpdateTime()
    {
        return $this->getData(self::UPDATE_TIME);
    }

    /**
     * Set UpdateTime.
     */
    public function setUpdateTime($updateTime)
    {
        return $this->setData(self::UPDATE_TIME, $updateTime);
    }

    /**
     * Get CreatedAt.
     *
     * @return varchar
     */
    public function getCreatedAt()
    {
        return $this->getData(self::CREATED_AT);
    }

    /**
     * Set CreatedAt.
     */
    public function setCreatedAt($createdAt)
    {
        return $this->setData(self::CREATED_AT, $createdAt);
    }
}

 

Step 7:  Create Model Interface File

Create The Interface file named GridExampleInterface.php on below path.
Path: app/code/Ak/GridExample/Api/Data

<?php
 /** GridExample GridExampleInterface
 * @category  Ak
 * @package   Ak_GridExample
 * @author    Ak
 * @copyright Copyright (c) 2005-2017 Adesh Suryan (https://adeshsuryan.in)
 * @license   http://www.opensource.org/licenses/gpl-2.0.php
 */ 

namespace Ak\GridExample\Api\Data;

interface GridExampleInterface
{
    /**
     * Constants for keys of data array.
     */
    const ENTITY_ID = 'entity_id';
    const TITLE = 'title';
    const CONTENT = 'content';
    const PUBLISH_DATE = 'publish_date';
    const IS_ACTIVE = 'is_active';
    const UPDATE_TIME = 'update_time';
    const CREATED_AT = 'created_at';

   /**
    * Get EntityId.
    *
    * @return int
    */
    public function getEntityId();

   /**
    * Set EntityId.
    */
    public function setEntityId($entityId);

   /**
    * Get Title.
    *
    * @return varchar
    */
    public function getTitle();

   /**
    * Set Title.
    */
    public function setTitle($title);

   /**
    * Get Content.
    *
    * @return varchar
    */
    public function getContent();

   /**
    * Set Content.
    */
    public function setContent($content);

   /**
    * Get Publish Date.
    *
    * @return varchar
    */
    public function getPublishDate();

   /**
    * Set PublishDate.
    */
    public function setPublishDate($publishDate);

   /**
    * Get IsActive.
    *
    * @return varchar
    */
    public function getIsActive();

   /**
    * Set IsActive.
    */
    public function setIsActive($isActive);

   /**
    * Get UpdateTime.
    *
    * @return varchar
    */
    public function getUpdateTime();

   /**
    * Set UpdateTime.
    */
    public function setUpdateTime($updateTime);

   /**
    * Get CreatedAt.
    *
    * @return varchar
    */
    public function getCreatedAt();

   /**
    * Set CreatedAt.
    */
    public function setCreatedAt($createdAt);
}

 

 

Step 9:  Create Resource Model File 

Create The Resource Model file named GridExample.php on below path.
Path: app/code/Ak/GridExample/Model/ResourceModel

 

<?php
/** GridExample GridExample ResourceModel
 * @category  Ak
 * @package   Ak_GridExample
 * @author    Ak
 * @copyright Copyright (c) 2005-2017 Adesh Suryan (https://adeshsuryan.in)
 * @license   http://www.opensource.org/licenses/gpl-2.0.php
 */ 
 
namespace Ak\GridExample\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;

/**
 * GridExample GridExample mysql resource.
 */
 
class GridExample extends AbstractDb
{
    /**
     * @var string
     */
    protected $_idFieldName = 'entity_id';
    /**
     * @var \Magento\Framework\Stdlib\DateTime\DateTime
     */
    protected $_date;

    /**
     * Construct.
     *
     * @param \Magento\Framework\Model\ResourceModel\Db\Context $context
     * @param \Magento\Framework\Stdlib\DateTime\DateTime       $date
     * @param string|null                                       $resourcePrefix
     */
    public function __construct(
        \Magento\Framework\Model\ResourceModel\Db\Context $context,
        \Magento\Framework\Stdlib\DateTime\DateTime $date,
        $resourcePrefix = null
    ) {
        parent::__construct($context, $resourcePrefix);
        $this->_date = $date;
    }

    /**
     * Initialize resource model.
     */
    protected function _construct()
    {
        $this->_init('ak_gridexample_records', 'entity_id');
    }
}

 

Step 10: Create Resource Collection File

Create The Collection file named Collection.php on below path.
Path: app/code/Ak/GridExample/Model/ResourceMode/GridExample

 

<?php
/** GridExample GridExample Collection
 * @category  Ak
 * @package   Ak_GridExample
 * @author    Ak
 * @copyright Copyright (c) 2005-2017 Adesh Suryan (https://adeshsuryan.in)
 * @license   http://www.opensource.org/licenses/gpl-2.0.php
 */ 
 
namespace Ak\GridExample\Model\ResourceModel\GridExample;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;

class Collection extends AbstractCollection
{
    /**
     * @var string
     */
    protected $_idFieldName = 'entity_id';
    /**
     * Define resource model.
     */
    protected function _construct()
    {
        $this->_init(
            \Ak\GridExample\Model\GridExample::class,
            \Ak\GridExample\Model\ResourceModel\GridExample::class
        );
    }
    protected function _initSelect() {
        parent::_initSelect();
        //@override the collection and add join 
       /* $this->getSelect()->joinLeft(
                ['xyz' => $this->getTable('xyz_table')],
                'xyz.pqr_id = main_table.entity_id',
                ['xy_column']
        );
        return $this; */
    }
}

 

Step 11: Create Admin Grid using Ui Component

Create Ui Component For Grid Row List, file named gridexample_record_grid_list.xml on below path.
Path: app/code/Ak/GridExample/View/Adminhtml/Ui_component

 

<?xml version="1.0" encoding="UTF-8"?>
<!--
/** GridExample record list UI Component
 * @category  Ak
 * @package   Ak_GridExample
 * @author    Ak
 * @copyright Copyright (c) 2005-2017 Adesh Suryan (https://adeshsuryan.in)
 * @license   http://www.opensource.org/licenses/gpl-2.0.php
 */
 */
-->
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Ui/etc/ui_configuration.xsd">
    <argument name="data" xsi:type="array">
        <item name="js_config" xsi:type="array">
            <item name="provider" xsi:type="string">gridexample_record_gridexample_list.gridexample_record_gridexample_list_data_source</item>
            <item name="deps" xsi:type="string">gridexample_record_gridexample_list.gridexample_record_gridexample_list_data_source</item>
        </item>
        <item name="spinner" xsi:type="string">gridexample_records_columns</item>
        <item name="buttons" xsi:type="array">
            <item name="add" xsi:type="array">
                <item name="name" xsi:type="string">add</item>
                <item name="label" xsi:type="string" translate="true">Add New Row</item>
                <item name="class" xsi:type="string">primary</item>
                <item name="url" xsi:type="string">*/*/addrow</item>
            </item>
        </item>
    </argument>
    <dataSource name="gridexample_record_gridexample_list_data_source">
        <argument name="dataProvider" xsi:type="configurableObject">
            <argument name="class" xsi:type="string">Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider</argument>
            <argument name="name" xsi:type="string">gridexample_record_gridexample_list_data_source</argument>
            <argument name="primaryFieldName" xsi:type="string">entity_id</argument>
            <argument name="requestFieldName" xsi:type="string">id</argument>
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="update_url" xsi:type="url" path="mui/index/render"/>
                </item>
            </argument>
        </argument>
        <argument name="data" xsi:type="array">
            <item name="js_config" xsi:type="array">
                <item name="component" xsi:type="string">Magento_Ui/js/grid/provider</item>
            </item>
        </argument>
    </dataSource>
    <container name="listing_top">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="template" xsi:type="string">ui/grid/toolbar</item>
                <item name="stickyTmpl" xsi:type="string">ui/grid/sticky/toolbar</item>
            </item>
        </argument>
        <bookmark name="bookmarks"/>
        <columnsControls name="columns_controls"/>
        <filters name="listing_filters">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="columnsProvider" xsi:type="string">gridexample_record_gridexample_list.gridexample_record_gridexample_list.gridexample_records_columns</item>
                    <item name="storageConfig" xsi:type="array">
                        <item name="provider" xsi:type="string">gridexample_record_gridexample_list.gridexample_record_gridexample_list.listing_top.bookmarks</item>
                        <item name="namespace" xsi:type="string">current.filters</item>
                    </item>
                    <item name="templates" xsi:type="array">
                        <item name="filters" xsi:type="array">
                            <item name="select" xsi:type="array">
                                <item name="component" xsi:type="string">Magento_Ui/js/form/element/ui-select</item>
                                <item name="template" xsi:type="string">ui/grid/filters/elements/ui-select</item>
                            </item>
                        </item>
                    </item>
                    <item name="childDefaults" xsi:type="array">
                        <item name="provider" xsi:type="string">gridexample_record_gridexample_list.gridexample_record_gridexample_list.listing_top.listing_filters</item>
                        <item name="imports" xsi:type="array">
                            <item name="visible" xsi:type="string">gridexample_record_gridexample_list.gridexample_record_gridexample_list.gridexample_records_columns.${ $.index }:visible</item>
                        </item>
                    </item>
                </item>
                <item name="observers" xsi:type="array">
                    <item name="column" xsi:type="string">column</item>
                </item>
            </argument>
        </filters>
        <massaction name="listing_massaction">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="selectProvider" xsi:type="string">gridexample_record_gridexample_list.gridexample_record_gridexample_list.gridexample_records_columns.ids</item>
                    <item name="component" xsi:type="string">Magento_Ui/js/grid/tree-massactions</item>
                    <item name="indexField" xsi:type="string">id</item>
                </item>
            </argument>
            <!-- Mass actions which you want to add in your grid-->
            <action name="delete">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="type" xsi:type="string">delete</item>
                        <item name="label" xsi:type="string" translate="true">Delete</item>
                        <item name="url" xsi:type="url" path="grid/grid/massdelete"/>
                        <item name="confirm" xsi:type="array">
                            <item name="title" xsi:type="string" translate="true">Delete</item>
                            <item name="message" xsi:type="string" translate="true">Do you want to delete selected row record?</item>
                        </item>
                    </item>
                </argument>
            </action>
        </massaction>
        <paging name="listing_paging">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="storageConfig" xsi:type="array">
                        <item name="provider" xsi:type="string">gridexample_record_gridexample_list.gridexample_record_gridexample_list.listing_top.bookmarks</item>
                        <item name="namespace" xsi:type="string">current.paging</item>
                    </item>
                    <item name="selectProvider" xsi:type="string">gridexample_record_gridexample_list.gridexample_record_gridexample_list.gridexample_records_columns.ids</item>
                </item>
            </argument>
        </paging>
    </container>
    <columns name="gridexample_records_columns">
        <selectionsColumn name="ids">
           <argument name="data" xsi:type="array">
               <item name="config" xsi:type="array">
                   <item name="indexField" xsi:type="string">entity_id</item>
                   <item name="sorting" xsi:type="string">desc</item>
                   <item name="sortOrder" xsi:type="number">0</item>
               </item>
           </argument>
       </selectionsColumn>
       <column name="title">
           <argument name="data" xsi:type="array">
               <item name="config" xsi:type="array">
                   <item name="filter" xsi:type="string">textRange</item>
                   <item name="label" xsi:type="string" translate="true">Title</item>
               </item>
           </argument>
       </column>
       <column name="content" >
           <argument name="data" xsi:type="array">
               <item name="config" xsi:type="array">
                   <item name="filter" xsi:type="string">false</item>
                   <item name="label" xsi:type="string" translate="true">Content</item>
               </item>
           </argument>
       </column>
       <column name="is_active" >
           <argument name="data" xsi:type="array">
               <item name="options" xsi:type="object">Ak\GridExample\Model\Status</item>
               <item name="config" xsi:type="array">
                   <item name="filter" xsi:type="string">select</item>
                   <item name="component" xsi:type="string">Magento_Ui/js/grid/columns/select</item>
                   <item name="dataType" xsi:type="string">select</item>
                   <item name="label" xsi:type="string" translate="true">Is Active</item>
               </item>
           </argument>
       </column>
       <column name="publish_date" class="Magento\Ui\Component\Listing\Columns\Date" >
           <argument name="data" xsi:type="array">
               <item name="config" xsi:type="array">
                   <item name="filter" xsi:type="string">dateRange</item>
                   <item name="component" xsi:type="string">Magento_Ui/js/grid/columns/date</item>
                   <item name="dataType" xsi:type="string">date</item>
                   <item name="label" xsi:type="string" translate="true">Publish Date</item>
               </item>
           </argument>
       </column>
       <column name="update_time" class="Magento\Ui\Component\Listing\Columns\Date" >
           <argument name="data" xsi:type="array">
               <item name="config" xsi:type="array">
                   <item name="filter" xsi:type="string">dateRange</item>
                   <item name="component" xsi:type="string">Magento_Ui/js/grid/columns/date</item>
                   <item name="dataType" xsi:type="string">date</item>
                   <item name="label" xsi:type="string" translate="true">Update Time</item>
               </item>
           </argument>
       </column>
       <column name="created_at" class="Magento\Ui\Component\Listing\Columns\Date" >
           <argument name="data" xsi:type="array">
               <item name="config" xsi:type="array">
                   <item name="filter" xsi:type="string">dateRange</item>
                   <item name="component" xsi:type="string">Magento_Ui/js/grid/columns/date</item>
                   <item name="dataType" xsi:type="string">date</item>
                   <item name="label" xsi:type="string" translate="true">Created At</item>
               </item>
           </argument>
       </column>
       <!-- Add Action with each row of grid and for this we will create a class Action -->
       <actionsColumn name="actions" class="Ak\GridExample\Ui\Component\Listing\GridExample\Column\Action">
           <argument name="data" xsi:type="array">
               <item name="config" xsi:type="array">
                   <item name="resizeEnabled" xsi:type="boolean">false</item>
                   <item name="resizeDefaultWidth" xsi:type="string">107</item>
                   <item name="indexField" xsi:type="string">id</item>
               </item>
           </argument>
       </actionsColumn>
    </columns>
</listing>

 

Step 12: Create Map Data File

Create Map Data file named di.Xml on below path.
Path: app/code/Ak/GridExample/etc

 

<?xml version="1.0"?>
<!--
/** GridExample di xml
 * @category  Ak
 * @package   Ak_GridExample
 * @author    Ak
 * @copyright Copyright (c) 2005-2017 Adesh Suryan (https://adeshsuryan.in)
 * @license   http://www.opensource.org/licenses/gpl-2.0.php
 */
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Ak\GridExample\Api\Data\GridExampleInterface" type="Ak\GridExample\Model\GridExample" />

    <virtualType name="Ak\GridExample\Model\ResourceModel\GridExample\Collection" type="Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult">
        <arguments>
            <argument name="mainTable" xsi:type="string">ak_gridexample_records</argument>
            <argument name="resourceModel" xsi:type="string">Ak\GridExample\Model\ResourceModel\GridExample</argument>
        </arguments>
    </virtualType>
    <type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
        <arguments>
            <argument name="collections" xsi:type="array">
                <item name="gridexample_record_grid_list_data_source" xsi:type="string">Ak\GridExample\Model\ResourceModel\GridExample\Collection</item>
            </argument>
        </arguments>
    </type>
    <type name="Ak\GridExample\Logger\Handler">
        <arguments>
            <argument name="filesystem" xsi:type="object">Magento\Framework\Filesystem\Driver\File</argument>
        </arguments>
    </type>
    <type name="Ak\GridExample\Logger\Logger">
        <arguments>
            <argument name="name" xsi:type="string">customLogHandler</argument>
            <argument name="handlers"  xsi:type="array">
                <item name="system" xsi:type="object">Ak\GridExample\Logger\Handler</item>
            </argument>
        </arguments>
    </type>
</config>

 

UI Action :

 

For Action Create Action Class Action.Php In App/Code/Ak/GridExample/Ui/Component/Listing/GridExample/Column

 

<?php
 /** GridExample Ui Component Action.
 * @category  Ak
 * @package   Ak_GridExample
 * @author    Ak
 * @copyright Copyright (c) 2005-2017 Adesh Suryan (https://adeshsuryan.in)
 * @license   http://www.opensource.org/licenses/gpl-2.0.php
 */ 
 
namespace Ak\GridExample\Ui\Component\Listing\Grid\Column;

use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Ui\Component\Listing\Columns\Column;
use Magento\Framework\UrlInterface;

class Action extends Column
{
    /** Url path */
    const ROW_EDIT_URL = 'gridexample/gridexample/addrow';
    /** @var UrlInterface */
    protected $_urlBuilder;

    /**
     * @var string
     */
    private $_editUrl;

    /**
     * @param ContextInterface   $context
     * @param UiComponentFactory $uiComponentFactory
     * @param UrlInterface       $urlBuilder
     * @param array              $components
     * @param array              $data
     * @param string             $editUrl
     */
    public function __construct(
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,
        UrlInterface $urlBuilder,
        array $components = [],
        array $data = [],
        $editUrl = self::ROW_EDIT_URL
    ) {
        $this->_urlBuilder = $urlBuilder;
        $this->_editUrl = $editUrl;
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }

    /**
     * Prepare Data Source.
     *
     * @param array $dataSource
     *
     * @return array
     */
    public function prepareDataSource(array $dataSource)
    {
        if (isset($dataSource['data']['items'])) {
            foreach ($dataSource['data']['items'] as &$item) {
                $name = $this->getData('name');
                if (isset($item['entity_id'])) {
                    $item[$name]['edit'] = [
                        'href' => $this->_urlBuilder->getUrl(
                            $this->_editUrl,
                            ['id' => $item['entity_id']]
                        ),
                        'label' => __('Edit'),
                    ];
                }
            }
        }

        return $dataSource;
    }
}

 

 

 

Step 13: Create “Create”,Save,MassDelete etc. Action Files

We need to create specific controller file for each  like  MassDelete.php for Mass Delete action etc.

Create list row controller file on below path with AddRow.php,
Path : app/code/Ak/GridExample/Controllers/Adminhtml/GridExample

<?php
/** GridExample List Controller
 * @category  Ak
 * @package   Ak_GridExample
 * @author    Ak
 * @copyright Copyright (c) 2005-2017 Adesh Suryan (https://adeshsuryan.in)
 * @license   http://www.opensource.org/licenses/gpl-2.0.php
 */
 
namespace Ak\GridExample\Controller\Adminhtml\GridExample;

use Magento\Framework\Controller\ResultFactory;

class AddRow extends \Magento\Backend\App\Action
{
    /**
     * @var \Magento\Framework\Registry
     */
    private $coreRegistry;

    /**
     * @var \Ak\GridExample\Model\GridFactory
     */
    private $gridFactory;

    /**
     * @param \Magento\Backend\App\Action\Context $context
     * @param \Magento\Framework\Registry $coreRegistry,
     * @param \Ak\GridExample\Model\GridFactory $gridFactory
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\Registry $coreRegistry,
        \Ak\GridExample\Model\GridFactory $gridFactory   
    ) {
        parent::__construct($context);
        $this->coreRegistry = $coreRegistry;
        $this->gridFactory = $gridFactory;
    }

    /**
     * Mapped Grid List page.
     * @return \Magento\Backend\Model\View\Result\Page
     */
    public function execute()
    {
        $rowId = (int) $this->getRequest()->getParam('id');
        $rowData = $this->gridFactory->create();
        /** @var \Magento\Backend\Model\View\Result\Page $resultPage */
        if ($rowId) {
            $rowData = $rowData->load($rowId);
            $rowTitle = $rowData->getTitle();
            if (!$rowData->getEntityId()) {
                $this->messageManager->addError(__('row data no longer exist.'));
                $this->_redirect('gridexample/gridexample/rowdata');
                return;
            }
        }

        $this->coreRegistry->register('row_data', $rowData);
        $resultPage = $this->resultFactory->create(ResultFactory::TYPE_PAGE);
        $title = $rowId ? __('Edit Row Data ').$rowTitle : __('Add Row Data');
        $resultPage->getConfig()->getTitle()->prepend($title);
        return $resultPage;
    }

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

 

Create Save  row controller file with Save.php,

 

<?php
/** GridExample Row Save Controller.
 * @category  Ak
 * @package   Ak_GridExample
 * @author    Ak
 * @copyright Copyright (c) 2005-2017 Adesh Suryan (https://adeshsuryan.in)
 * @license   http://www.opensource.org/licenses/gpl-2.0.php
 */
namespace Ak\GridExampl\Controller\Adminhtml\GridExampl;

class Save extends \Magento\Backend\App\Action
{
    /**
     * @var \Ak\GridExampl\Model\GridFactory
     */
    var $gridFactory;

    /**
     * @param \Magento\Backend\App\Action\Context $context
     * @param \Ak\GridExampl\Model\GridFactory $gridFactory
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Ak\GridExampl\Model\GridFactory $gridFactory
    ) {
        parent::__construct($context);
        $this->gridFactory = $gridFactory;
    }

    /**
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */
    public function execute()
    {
        $data = $this->getRequest()->getPostValue();
        if (!$data) {
            $this->_redirect('gridexample/gridexample/addrow');
            return;
        }
        try {
            $rowData = $this->gridFactory->create();
            $rowData->setData($data);
            if (isset($data['id'])) {
                $rowData->setEntityId($data['id']);
            }
            $rowData->save();
            $this->messageManager->addSuccess(__('Row data has been successfully saved.'));
        } catch (\Exception $e) {
            $this->messageManager->addError(__($e->getMessage()));
        }
        $this->_redirect('gridexample/gridexample/index');
    }

    /**
     * @return bool
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('Ak_GridExampl::save');
    }
}

Create a INDEX.php file on same path  by which we can prepare and/or invoke  UI Component And Data Provider.

 

<?php
/** GridExample Row Index Controller.
 * @category  Ak
 * @package   Ak_GridExample
 * @author    Ak
 * @copyright Copyright (c) 2005-2017 Adesh Suryan (https://adeshsuryan.in)
 * @license   http://www.opensource.org/licenses/gpl-2.0.php
 */ 
namespace Ak\GridExampl\Controller\Adminhtml\GridExampl;

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;
    }

    /**
     * Mapped eBay Order List page.
     *
     * @return \Magento\Backend\Model\View\Result\Page
     */
    public function execute()
    {
        $resultPage = $this->resultPageFactory->create();
        $resultPage->setActiveMenu('Ak_GridExampl::grid_list');
        $resultPage->getConfig()->getTitle()->prepend(__('Grid List'));
        return $resultPage;
    }

    /**
     * Check Order Import Permission.
     *
     * @return bool
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('Ak_GridExampl::grid_list');
    }
}

 

Create a file by which we can delete multiple rows . File name as MassDelete.php.

<?php
/** GridExample Rows Delete Controller.
 * @category  Ak
 * @package   Ak_GridExample
 * @author    Ak
 * @copyright Copyright (c) 2005-2017 Adesh Suryan (https://adeshsuryan.in)
 * @license   http://www.opensource.org/licenses/gpl-2.0.php
 */  
namespace Ak\GridExampl\Controller\Adminhtml\GridExampl;

use Magento\Framework\Controller\ResultFactory;
use Magento\Backend\App\Action\Context;
use Magento\Ui\Component\MassAction\Filter;
use  Ak\GridExampl\Model\ResourceModel\GridExampl\CollectionFactory;

class MassDelete extends \Magento\Backend\App\Action
{
    /**
     * Massactions filter.
     * @var Filter
     */
    protected $_filter;

    /**
     * @var CollectionFactory
     */
    protected $_collectionFactory;

    /**
     * @param Context           $context
     * @param Filter            $filter
     * @param CollectionFactory $collectionFactory
     */
    public function __construct(
        Context $context,
        Filter $filter,
        CollectionFactory $collectionFactory
    ) {

        $this->_filter = $filter;
        $this->_collectionFactory = $collectionFactory;
        parent::__construct($context);
    }

    /**
     * @return \Magento\Backend\Model\View\Result\Redirect
     */
    public function execute()
    {
        $collection = $this->_filter->getCollection($this->_collectionFactory->create());
        $recordDeleted = 0;
        foreach ($collection->getItems() as $record) {
            $record->setId($record->getEntityId());
            $record->delete();
            $recordDeleted++;
        }
        $this->messageManager->addSuccess(__('A total of %1 record(s) have been deleted.', $recordDeleted));

        return $this->resultFactory->create(ResultFactory::TYPE_REDIRECT)->setPath('*/*/index');
    }

    /**
     * Check Category Map recode delete Permission.
     * @return bool
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('Ak_GridExampl::row_data_delete');
    }
}

 

 

 

Step 14: Create Option status file

Create Status.Php on below path for status option
Path : App/Code/Ak/GridExample/Model

<?php
/** GridExample Status Options Model.
 * @category  Ak
 * @package   Ak_GridExample
 * @author    Ak
 * @copyright Copyright (c) 2005-2017 Adesh Suryan (https://adeshsuryan.in)
 * @license   http://www.opensource.org/licenses/gpl-2.0.php
 */   
namespace Ak\GridExampl\Model;

use Magento\Framework\Data\OptionSourceInterface;

class Status implements OptionSourceInterface
{
    /**
     * Get Grid row status type labels array.
     * @return array
     */
    public function getOptionArray()
    {
        $options = ['1' => __('Enabled'),'0' => __('Disabled')];
        return $options;
    }

    /**
     * Get Grid row status labels array with empty value for option element.
     *
     * @return array
     */
    public function getAllOptions()
    {
        $res = $this->getOptions();
        array_unshift($res, ['value' => '', 'label' => '']);
        return $res;
    }

    /**
     * Get Grid row type array for option element.
     * @return array
     */
    public function getOptions()
    {
        $res = [];
        foreach ($this->getOptionArray() as $index => $value) {
            $res[] = ['value' => $index, 'label' => $value];
        }
        return $res;
    }

    /**
     * {@inheritdoc}
     */
    public function toOptionArray()
    {
        return $this->getOptions();
    }
}

 

Step 15: Create Route File Routes.Xml on below path.
Path : App/Code/Ak/GridExample/etc/Adminhtml

 

<?xml version="1.0"?>
<!--
/** GridExample adminhtml routes xml
 * @category  Ak
 * @package   Ak_GridExample
 * @author    Ak
 * @copyright Copyright (c) 2005-2017 Adesh Suryan (https://adeshsuryan.in)
 * @license   http://www.opensource.org/licenses/gpl-2.0.php
 */
-->


<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="admin">
        <route id="gridexampl" frontName="gridexampl">
            <module name="Ak_GridExampl" />
        </route>
    </router>
</config>

Step 16: Create Grid Display Layout File gridexampl_gridexampl_index.xml on below path.
Path : App/Code/Ak/GridExample/View/Adminhtml/Layout

<?xml version="1.0"?>
<!--
 /** GridExample adminhtml Layout xml
 * @category  Ak
 * @package   Ak_GridExample
 * @author    Ak
 * @copyright Copyright (c) 2005-2017 Adesh Suryan (https://adeshsuryan.in)
 * @license   http://www.opensource.org/licenses/gpl-2.0.php
 */
-->
<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">
            <!-- here we call our ui component of grid-->
            <uiComponent name="gridexample_record_gridexample_list"/>
        </referenceContainer>
    </body>
</page>

 

Step 17: Create Block File for Save/Edit Data process file

Note : Make sure all controller file should available before the block.

a)

Create Block File Of Form AddRow.Php on below path.
Path: App/Code/Ak/GridExample/Block/Adminhtml/GridExample/

 

<?php
/** GridExample Add block for Row list
 * @category  Ak
 * @package   Ak_GridExample
 * @author    Ak
 * @copyright Copyright (c) 2005-2017 Adesh Suryan (https://adeshsuryan.in)
 * @license   http://www.opensource.org/licenses/gpl-2.0.php
 */
 
namespace Ak\GridExample\Block\Adminhtml\GridExample;

class AddRow extends \Magento\Backend\Block\Widget\Form\Container
{
    /**
     * Core registry.
     *
     * @var \Magento\Framework\Registry
     */
    protected $_coreRegistry = null;

    /**
     * @param \Magento\Backend\Block\Widget\Context $context
     * @param \Magento\Framework\Registry           $registry
     * @param array                                 $data
     */
    public function __construct(
        \Magento\Backend\Block\Widget\Context $context,
        \Magento\Framework\Registry $registry,
        array $data = []
    ) {
        $this->_coreRegistry = $registry;
        parent::__construct($context, $data);
    }

    /**
     * Initialize Imagegallery Images Edit Block.
     */
    protected function _construct()
    {
        $this->_objectId = 'row_id';
        $this->_blockGroup = 'Ak_GridExample';
        $this->_controller = 'adminhtml_grid';
        parent::_construct();
        if ($this->_isAllowedAction('Ak_GridExample::add_row')) {
            $this->buttonList->update('save', 'label', __('Save'));
        } else {
            $this->buttonList->remove('save');
        }
        $this->buttonList->remove('reset');
    }

    /**
     * Retrieve text for header element depending on loaded image.
     *
     * @return \Magento\Framework\Phrase
     */
    public function getHeaderText()
    {
        return __('Add RoW Data');
    }

    /**
     * Check permission for passed action.
     *
     * @param string $resourceId
     *
     * @return bool
     */
    protected function _isAllowedAction($resourceId)
    {
        return $this->_authorization->isAllowed($resourceId);
    }

    /**
     * Get form action URL.
     *
     * @return string
     */
    public function getFormActionUrl()
    {
        if ($this->hasFormActionUrl()) {
            return $this->getData('form_action_url');
        }

        return $this->getUrl('*/*/save');
    }
}

 

 

b)
Create Block File Of Form With Field Form.Php on below path.
Path : App/Code/Ak/GridExample/Block/Adminhtml/GridExample/Edit

<?php
/** GridExample Add edit form block for Row list
 * @category  Ak
 * @package   Ak_GridExample
 * @author    Ak
 * @copyright Copyright (c) 2005-2017 Adesh Suryan (https://adeshsuryan.in)
 * @license   http://www.opensource.org/licenses/gpl-2.0.php
 */
namespace Ak\GridExample\Block\Adminhtml\GridExample\Edit;

/**
 * Adminhtml Add New Row Form.
 */
class Form extends \Magento\Backend\Block\Widget\Form\Generic
{
    /**
     * @var \Magento\Store\Model\System\Store
     */
    protected $_systemStore;

    /**
     * @param \Magento\Backend\Block\Template\Context $context,
     * @param \Magento\Framework\Registry $registry,
     * @param \Magento\Framework\Data\FormFactory $formFactory,
     * @param \Magento\Cms\Model\Wysiwyg\Config $wysiwygConfig,
     * @param \Ak\GridExample\Model\Status $options,
     */
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Data\FormFactory $formFactory,
        \Magento\Cms\Model\Wysiwyg\Config $wysiwygConfig,
        \Ak\GridExample\Model\Status $options,
        array $data = []
    ) {
        $this->_options = $options;
        $this->_wysiwygConfig = $wysiwygConfig;
        parent::__construct($context, $registry, $formFactory, $data);
    }

    /**
     * Prepare form.
     *
     * @return $this
     */
    protected function _prepareForm()
    {
        $dateFormat = $this->_localeDate->getDateFormat(\IntlDateFormatter::SHORT);
        $model = $this->_coreRegistry->registry('row_data');
        $form = $this->_formFactory->create(
            ['data' => [
                            'id' => 'edit_form',
                            'enctype' => 'multipart/form-data',
                            'action' => $this->getData('action'),
                            'method' => 'post'
                        ]
            ]
        );

        $form->setHtmlIdPrefix('akgrid_');
        if ($model->getEntityId()) {
            $fieldset = $form->addFieldset(
                'base_fieldset',
                ['legend' => __('Edit Row Data'), 'class' => 'fieldset-wide']
            );
            $fieldset->addField('entity_id', 'hidden', ['name' => 'entity_id']);
        } else {
            $fieldset = $form->addFieldset(
                'base_fieldset',
                ['legend' => __('Add Row Data'), 'class' => 'fieldset-wide']
            );
        }

        $fieldset->addField(
            'title',
            'text',
            [
                'name' => 'title',
                'label' => __('Title'),
                'id' => 'title',
                'title' => __('Title'),
                'class' => 'required-entry',
                'required' => true,
            ]
        );

        $wysiwygConfig = $this->_wysiwygConfig->getConfig(['tab_id' => $this->getTabId()]);

        $fieldset->addField(
            'content',
            'editor',
            [
                'name' => 'content',
                'label' => __('Content'),
                'style' => 'height:36em;',
                'required' => true,
                'config' => $wysiwygConfig
            ]
        );

        $fieldset->addField(
            'publish_date',
            'date',
            [
                'name' => 'publish_date',
                'label' => __('Publish Date'),
                'date_format' => $dateFormat,
                'time_format' => 'H:mm:ss',
                'class' => 'validate-date validate-date-range date-range-custom_theme-from',
                'class' => 'required-entry',
                'style' => 'width:200px',
            ]
        );
        $fieldset->addField(
            'is_active',
            'select',
            [
                'name' => 'is_active',
                'label' => __('Status'),
                'id' => 'is_active',
                'title' => __('Status'),
                'values' => $this->_options->getOptionArray(),
                'class' => 'status',
                'required' => true,
            ]
        );
        $form->setValues($model->getData());
        $form->setUseContainer(true);
        $this->setForm($form);

        return parent::_prepareForm();
    }
}

Step 18: Create Layout File for Render the Form

Create Layout File for addrow form gridexampl_gridexampl_addrow.Xml on below path. Path: App/Code/Ak/GridExample/View/Adminhtml/Layout

<?xml version="1.0"?>
<!--
/** GridExample adminhtml Layout xml
 * @category  Ak
 * @package   Ak_GridExample
 * @author    Ak
 * @copyright Copyright (c) 2005-2017 Adesh Suryan (https://adeshsuryan.in)
 * @license   http://www.opensource.org/licenses/gpl-2.0.php
 */ 
-->
<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="Ak\GridExample\Block\Adminhtml\GridExample\AddRow" name="add_row" />
        </referenceContainer>
    </body>
</page>

 

……………………………………………….

Leave a Reply

Your email address will not be published.