Loading...

How to Create Crud Operations in Grid?

Jayram Prajapati  ·   20 Dec 2022
How to Create Crud Operations in Grid?
service-banner

Introduction

How to edit, update, delete, and add new data in Grid in Backend

  • First Create a Grid in your module
  • Then Create CRUD operation on your Grid

 

Create, Add, Delete, Save, and Edit files in your Controller

        (1) Create an Add.php file at the following location:

                -> app/code/Elightwalk/CustomGrid/Controller/Adminhtml/CustomerInfo/Add.php

php

<?php

namespace Elightwalk\CustomGrid\Controller\Adminhtml\CustomerInfo;

use Magento\Framework\Controller\ResultFactory;

class Add extends \Magento\Backend\App\Action

{

          public function execute()

          {

                 $resultPage = $this->resultFactory->create(ResultFactory::TYPE_PAGE);

                 $resultPage->getConfig()->getTitle()->prepend(__('Add New Data'));

                  return $resultPage;

         }

}

(2) Create a Delete.php file at the following location:

-> app/code/Elightwalk/CustomGrid/Controller/Adminhtml/CustomerInfo/Delete.php

php

<?php

namespace Elightwalk\CustomGrid\Controller\Adminhtml\CustomerInfo;

 

use Magento\Backend\App\Action;

use Magento\Backend\App\Action\Context;

class Delete extends Action

{

protected $modelGrid;

public function __construct(

               Context $context,

               \Elightwalk\CustomGrid\Model\CustomerInfo $gridFactory

) {

               parent::__construct($context);

               $this->modelGrid = $gridFactory;

}

protected function _isAllowed()

{

               return $this->_authorization->isAllowed('Elightwalk_CustomGrid::index_delete');

}

public function execute()

{

               $id = $this->getRequest()->getParam('id');

               $resultRedirect = $this->resultRedirectFactory->create();

               if ($id) {

                          try {

                                     $model = $this->modelGrid;

                                     $model->load($id);

                                     $model->delete();

                                     $this->messageManager->addSuccess(__('Record deleted successfully.'));

                                     return $resultRedirect->setPath('*/*/');

                          } catch (\Exception $e) {

                                      $this->messageManager->addError($e->getMessage());

                                       return $resultRedirect->setPath('*/*/edit', ['id' => $id]);

                          }

                 }

                $this->messageManager->addError(__('Record does not exist.'));

                return $resultRedirect->setPath('*/*/');

       }

}

(3) Create a Save.php file at the following location:

-> app/code/Elightwalk/CustomGrid/Controller/Adminhtml/CustomerInfo/Save.php

php

<?php

namespace Elightwalk\CustomGrid\Controller\Adminhtml\CustomerInfo;

 

use Magento\Backend\App\Action;

use Magento\Backend\Model\Session;

use Elightwalk\CustomGrid\Model\CustomerInfo;

 

class Save extends \Magento\Backend\App\Action

{

            protected $menumodel;

            protected $adminsession;

            protected $resultRedirect;

            public function __construct(

                        Action\Context $context,

                        CustomerInfo $menumodel,

                        Session $adminsession)

                 {

                        parent::__construct($context);

                        $this->menumodel = $menumodel;

                        $this->adminsession = $adminsession;

                }

                        public function execute()

               {

                        $data = $this->getRequest()->getParams();

                        if ($data)

                        {

                                    $id = $this->getRequest()->getParam('id');

                                    if ($id) {

                                                $this->menumodel->load($id);

                                    }

 

                                                $this->menumodel->setData($data);

 

                                    try {

                                                $this->menumodel->save();

                                                $this->messageManager->addSuccess(__('Data Saved.'));

                                                $this->adminsession->setFormData(false);

                                                if ($this->getRequest()->getParam('back')) {

                                                            $this->_redirect('*/*/edit', array('id' => $model->getId(), '_current' => true));

                                                            return;

                                                }

                                                $this->_redirect('*/*/');

                                                return;

                                    } catch (\Magento\Framework\Model\Exception $e) {

                                                $this->messageManager->addError($e->getMessage());

                                    } catch (\RuntimeException $e) {

                                                $this->messageManager->addError($e->getMessage());

                                    } catch (\Exception $e) {

                                                $this->messageManager->addException($e, __('Something went wrong while saving the banner.'));

                                    }

 

                                    $this->_getSession()->setFormData($data);

                                    $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));

                                    return;

                        }

                        $this->_redirect('*/*/');

            }

}

(4) Create an Edit.php file at the following location:

-> app/code/Elightwalk/CustomGrid/Controller/Adminhtml/CustomerInfo/Edit.php

php

<?php

namespace Elightwalk\CustomGrid\Controller\Adminhtml\CustomerInfo;

use Magento\Framework\Controller\ResultFactory;

class Edit extends \Magento\Backend\App\Action

{

   public function execute(){

       $resultPage = $this->resultFactory->create(ResultFactory::TYPE_PAGE);

       $resultPage->getConfig()->getTitle()->prepend(__('Edit Data'));

       return $resultPage;
   }

}

Create Block Folder With Below Files

(5) Create an UrlBuilder.php file at the following location:

-> app/code/Elightwalk/CustomGrid/Block/Adminhtml/Module/Grid/Renderer/Action/UrlBuilder.php

 

php

<?php

namespace Elightwalk\CustomGrid\Block\Adminhtml\Module\Grid\Renderer\Action;

class UrlBuilder {

          /**

          * @var \Magento\Framework\UrlInterface

          */

          protected $frontendUrlBuilder;

          /**

          * @param \Magento\Framework\UrlInterface $frontendUrlBuilder

          */

          public function __construct(\Magento\Framework\UrlInterface $frontendUrlBuilder) {

                    $this->frontendUrlBuilder = $frontendUrlBuilder;

          }

          /**

          * Get action url

          *

          * @param string $routePath

          * @param string $scope

          * @param string $store

          * @return string

          */

          public function getUrl($routePath, $scope, $store) {

                    $this->frontendUrlBuilder->setScope($scope);

                    $href = $this->frontendUrlBuilder->getUrl($routePath, ['_current' => false, '_query' => '___store=' . $store]);

                    return $href;

          }

}

(6) Create a Back.php file at the following location:

-> app/code/Elightwalk/CustomGrid/Block/Adminhtml/Grid/Edit/Button/Back.php

js

namespace Elightwalk\CustomGrid\Block\Adminhtml\Module\Grid\Renderer\Action;

class UrlBuilder {

          /**

          * @var \Magento\Framework\UrlInterface

          */

          protected $frontendUrlBuilder;

          /**

          * @param \Magento\Framework\UrlInterface $frontendUrlBuilder

          */

          public function __construct(\Magento\Framework\UrlInterface $frontendUrlBuilder) {

                    $this->frontendUrlBuilder = $frontendUrlBuilder;

          }

          /**

          * Get action url

          *

          * @param string $routePath

          * @param string $scope

          * @param string $store

          * @return string

          */

          public function getUrl($routePath, $scope, $store) {

                    $this->frontendUrlBuilder->setScope($scope);

                    $href = $this->frontendUrlBuilder->getUrl($routePath, ['_current' => false, '_query' => '___store=' . $store]);

                    return $href;

          }

}

(7) Create an Edit.php file at the following location:

-> app/code/Elightwalk/CustomGrid/Block/Adminhtml/Grid/Edit/Button/Edit.php

php

<?php

namespace Elightwalk\CustomGrid\Block\Adminhtml\Grid\Edit\Button;

 

/**

* CMS block edit form container

*/

class Edit extends \Magento\Backend\Block\Widget\Form\Container

{

          protected function _construct()

          {

                              $this->_objectId = 'id';

                    $this->_blockGroup = 'Elightwalk_CustomGrid';

                    $this->_controller = 'adminhtml_grid';

 

                    parent::_construct();

 

                    $this->buttonList->update('save', 'label', __('Save Block'));

                    $this->buttonList->update('delete', 'label', __('Delete Block'));

 

                    $this->buttonList->add(

                              'saveandcontinue',

                              array(

                                        'label' => __('Save and Continue Edit'),

                                        'class' => 'save',

                                        'data_attribute' => array(

                                                  'mage-init' => array('button' => array('event' => 'saveAndContinueEdit', 'target' => '#edit_form'))

                                        )

                              ),

                              -100

                    );

 

                    $this->_formScripts[] = "

                              function toggleEditor() {

                                        if (tinyMCE.getInstanceById('block_content') == null) {

                                                  tinyMCE.execCommand('mceAddControl', false, 'hello_content');

                                        } else {

                                                  tinyMCE.execCommand('mceRemoveControl', false, 'hello_content');

                                        }

                              }

                    ";

          }

 

          /**

          * Get edit form container header text

          *

          * @return string

          */

          public function getHeaderText()

          {

                    if ($this->_coreRegistry->registry('checkmodule_checkmodel')->getId()) {

                    return __("Edit Item '%1'", $this->escapeHtml($this->_coreRegistry->registry('checkmodule_checkmodel')->getTitle()));

                    } else {

                              return __('New Item');

                    }

          }

}

(8) Create a Generic.php file at the following location:

-> app/code/Elightwalk/CustomGrid/Block/Adminhtml/Grid/Edit/Button/Generic.php

php

<?php

namespace Elightwalk\CustomGrid\Block\Adminhtml\Grid\Edit\Button;

 

use Magento\Backend\Block\Widget\Context;

 

class Generic

{

          protected $context;

          public function __construct(

                    Context $context

          ) {

                    $this->context = $context;

          }

          public function getUrl($route = '', $params = [])

          {

                    return $this->context->getUrlBuilder()->getUrl($route, $params);

          }

}

(9) Create a Save.php file at the following location:

-> app/code/Elightwalk/CustomGrid/Block/Adminhtml/Grid/Edit/Button/Save.php

php

<?php

namespace Elightwalk\CustomGrid\Block\Adminhtml\Grid\Edit\Button;

 

use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;

use Magento\Ui\Component\Control\Container;

 

class Save extends Generic implements ButtonProviderInterface

{

          public function getButtonData()

          {

 

                    return [

                              'label' => __('Save'),

                              'class' => 'save primary',

                              'data_attribute' => [

                                        'mage-init' => [

                                                  'buttonAdapter' => [

                                                            'actions' => [

                                                                      [

                                                                                'targetName' => 'elightwalk_custom_grid_form.elightwalk_custom_grid_form.xml',

                                                                                'actionName' => 'save',

                                                                                'params' => [false],

                                                                      ],

                                                            ],

                                                  ],

                                        ],

                              ],

                    ];

          }

}

(10) Create an UrlBuilder.php file at the following location:

-> app/code/Elightwalk/CustomGrid/Block/Adminhtml/Module/Grid/Renderer/Action/UrlBuilder.php

php

<?php

namespace Elightwalk\CustomGrid\Block\Adminhtml\Module\Grid\Renderer\Action;

class UrlBuilder {

          /**

          * @var \Magento\Framework\UrlInterface

          */

          protected $frontendUrlBuilder;

          /**

          * @param \Magento\Framework\UrlInterface $frontendUrlBuilder

          */

          public function __construct(\Magento\Framework\UrlInterface $frontendUrlBuilder) {

                    $this->frontendUrlBuilder = $frontendUrlBuilder;

          }

          /**

          * Get action url

          *

          * @param string $routePath

          * @param string $scope

          * @param string $store

          * @return string

          */

          public function getUrl($routePath, $scope, $store) {

                    $this->frontendUrlBuilder->setScope($scope);

                    $href = $this->frontendUrlBuilder->getUrl($routePath, ['_current' => false, '_query' => '___store=' . $store]);

                    return $href;

          }

}

(11) Create elightwalk_custom_grid_listing.xml file at the following location: 

-> app/code/Elightwalk/CustomGrid/app/code/Elightwalk/CustomGrid/view/adminhtml/ui_component/elightwalk_custom_grid_listing.xml

xml

<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">

    <argument name="data" xsi:type="array">

        <item name="js_config" xsi:type="array">

            <item name="provider" xsi:type="string">elightwalk_custom_grid_form.elightwalk_custom_grid_form_data_source

            </item>

            <item name="deps" xsi:type="string">elightwalk_custom_grid_form.elightwalk_custom_grid_form_data_source

            </item>

        </item>

        <item name="label" xsi:type="string" translate="true">Form</item>

        <item name="config" xsi:type="array">

            <item name="dataScope" xsi:type="string">data</item>

            <item name="namespace" xsi:type="string">elightwalk_custom_grid_form</item>

        </item>

        <item name="spinner" xsi:type="string">Add Data</item>

        <item name="buttons" xsi:type="array">

            <item name="save" xsi:type="string">Elightwalk\CustomGrid\Block\Adminhtml\Grid\Edit\Button\Save</item>

            <item name="back" xsi:type="string">Elightwalk\CustomGrid\Block\Adminhtml\Grid\Edit\Button\Back</item>

        </item>

        <item name="template" xsi:type="string">templates/form/collapsible</item>

    </argument>

    <dataSource name="elightwalk_custom_grid_form_data_source">

        <argument name="dataProvider" xsi:type="configurableObject">

            <argument name="class" xsi:type="string">Elightwalk\CustomGrid\Model\DataProvider</argument>

            <argument name="name" xsi:type="string">elightwalk_custom_grid_form_data_source</argument>

            <argument name="primaryFieldName" xsi:type="string">id</argument>

            <argument name="requestFieldName" xsi:type="string">id</argument>

            <argument name="data" xsi:type="array">

                <item name="config" xsi:type="array">

                    <item name="submit_url" xsi:type="url" path="*/*/save" />

                </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/form/provider</item>

            </item>

        </argument>

    </dataSource>

    <fieldset name="form">

        <argument name="data" xsi:type="array">

            <item name="config" xsi:type="array">

                <item name="collapsible" xsi:type="boolean">false</item>

                <item name="label" xsi:type="string" translate="true">Form</item>

            </item>

        </argument>

        <!-- <field name="id">

       <argument name="data" xsi:type="array">

       <item name="config" xsi:type="array">

       <item name="visible" xsi:type="boolean">true</item>

       <item name="label" xsi:type="string">id</item>

       <item name="dataType" xsi:type="string">text</item>

       <item name="formElement" xsi:type="string">input</item>

       <item name="source" xsi:type="string">contact</item>

       </item>

       </argument>

       </field> -->

        <field name="productid">

            <argument name="data" xsi:type="array">

                <item name="config" xsi:type="array">

                    <item name="label" xsi:type="string">ProductId</item>

                    <item name="visible" xsi:type="boolean">true</item>

                    <item name="dataType" xsi:type="string">text</item>

                    <item name="formElement" xsi:type="string">input</item>

                    <item name="source" xsi:type="string">productid</item>

                </item>

            </argument>

        </field>

        <field name="contact_number">

            <argument name="data" xsi:type="array">

                <item name="config" xsi:type="array">

                    <item name="label" xsi:type="string">Contact_Number</item>

                    <item name="visible" xsi:type="boolean">true</item>

                    <item name="dataType" xsi:type="string">text</item>

                    <item name="formElement" xsi:type="string">input</item>

                    <item name="source" xsi:type="string">contact_number</item>

                </item>

            </argument>

        </field>

        <field name="email">

            <argument name="data" xsi:type="array">

                <item name="config" xsi:type="array">

                    <item name="label" xsi:type="string">Email</item>

                    <item name="visible" xsi:type="boolean">true</item>

                    <item name="dataType" xsi:type="string">text</item>

                    <item name="formElement" xsi:type="string">input</item>

                    <item name="source" xsi:type="string">email</item>

                </item>

            </argument>

        </field>

    </fieldset>

</form>

(12) Create a category_form.xml file at the following location:

->   app/code/Elightwalk/CustomGrid/app/code/Elightwalk/CustomGrid/view/adminhtml/ui_component/category_form.xml

For the action elightwalk_customgrid/post/index, we will create a file name elightwalk_customgrid_customerinfo_edit.xml

-> app/code/Elightwalk/CustomGrid/view/adminhtml/layout/elightwalk_customgrid_customerinfo_edit.xml

xml

<?xml version="1.0" ?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
   <fieldset name="content">
       <!-- <field name="elightwalk_option">
           <argument name="data" xsi:type="array">
               <item name="options" xsi:type="object">Elightwalk\CustomGrid\Model\Config\Source\Options</item>
               <item name="config" xsi:type="array">
                   <item name="sortOrder" xsi:type="number">40</item>
                   <item name="dataType" xsi:type="string">string</item>
                   <item name="formElement" xsi:type="string">select</item>
                   <item name="label" xsi:type="string" translate="true">Elightwalk_Options</item>
               </item>
           </argument>
       </field>
-->

   <field name="elightwalk_object">
   <argument name="data" xsi:type="array">
       <item name="config" xsi:type="array">
           <item name="sortOrder" xsi:type="number">10</item>
           <item name="dataType" xsi:type="string">boolean</item>
           <item name="formElement" xsi:type="string">checkbox</item>
           <item name="source" xsi:type="string">category</item>
           <item name="prefer" xsi:type="string">toggle</item>
           <item name="label" xsi:type="string" translate="true">Elightwalk_Object</item>
           <item name="valueMap" xsi:type="array">
               <item name="true" xsi:type="string">1</item>
               <item name="false" xsi:type="string">0</item>
           </item>
           <item name="validation" xsi:type="array">
               <item name="required-entry" xsi:type="boolean">false</item>
           </item>
           <item name="default" xsi:type="string">1</item>
       </item>
   </argument>
 </field>
</fieldset>
</form>

Create Layout Folder

(13) For the action elightwalk_customgrid/post/index, we will create a file name elightwalk_customgrid_customerinfo_newaction.xml

-> app/code/Elightwalk/CustomGrid/view/adminhtml/layout/elightwalk_customgrid_customerinfo_newaction.xml

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="elightwalk_customgrid_customerinfo_edit" />
</page>
 

(14) For the action elightwalk_customgrid/post/index, we will create a file name elightwalk_customgrid_customerinfo_edit.xml

-> app/code/Elightwalk/CustomGrid/view/adminhtml/layout/elightwalk_customgrid_customerinfo_edit.xml

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="styles" />
   <update handle="editor" />
   <body>
       <referenceContainer name="content">
           <uiComponent name="elightwalk_custom_grid_form" />
       </referenceContainer>    
   </body>
</page>

(15) For the action elightwalk_customgrid/post/index, we will create a file name elightwalk_customgrid_customerinfo_add.xml

-> app/code/Elightwalk/CustomGrid/view/adminhtml/layout/elightwalk_customgrid_customerinfo_add.xml

xml

<?xml version="1.0"?>
<!--
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left"  xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
<head>
    <title>
           Form
    </title>
</head>
<body>
    <referenceContainer name="content">
        <uiComponent name="elightwalk_custom_grid_form"/>
    </referenceContainer>
</body>
</page>

Then apply cache clean cmd

  • php bin/magento cache:clean

 

If your changes do not apply then try setup upgrade, setup compile, and static:content:deploy cmd

  • php bin/magento setup:upgrade
  • php bin/magento setup:di:compile
  • php bin/magento setup:static-content:deploy -f

 

Contact us:+91 8128405131

Email send us at hello@elightwalk.com

Jayram Prajapati
Full Stack Developer

Jayram Prajapati brings expertise and innovation to every project he takes on. His collaborative communication style, coupled with a receptiveness to new ideas, consistently leads to successful project outcomes.

Most Visited Blog

The Ultimate Guide to Cart Checkout GraphQL

With Ultimate Guide to GraphQL, you can dive into the realm of Cart Checkout. Discover the power of simplified interactions, frictionless transactions, and enhanced user experiences.

New Email Sender Requirements from Gmail & Yahoo: What You Should Know

Keep up to date on the most recent email sender criteria from Gmail and Yahoo. Learn how to protect your emails, increase deliver ability, and avoid potential problems.