Looking for Waste Management Solutions? Get Waste Management Solutions for Big Sale -50% off.

Iowa, USA

Kathmandu, Nepal

Pokhara, Nepal

+977 061-572157

How to Perform CRUD Operations in Magento 2

  • August 27, 2024
  • 7 min read

Coverage:

  1. File and Folder Structure
  2. Set Up Your Module
  3. Define the Database Schema
  4. Create the Model, ResourceModel, and Collection
  5. Implement CRUD Operations
  6. Summary

Introduction: 

Magento 2 is a powerful e-commerce platform that allows developers to create custom modules to extend its functionality. As an open-source solution, it offers robust capabilities and a highly flexible architecture, making it a popular choice for online retailers. One of the most common tasks when developing a module is performing CRUD operations, which stands for Create, Read, Update, and Delete. These operations are fundamental for managing data in any application, and understanding how to implement them in Magento 2 is crucial for developers looking to build and maintain effective e-commerce solutions.

File and Folder Structure:

app
└── code
    └── Nipuna
        └── SaloonChain
            ├── Block
            │   └── Saloon.php
            ├── Controller
            │   └── Adminhtml
            │       └── Saloon
            │           ├── Delete.php
            │           ├── Edit.php
            │           ├── Index.php
            │           └── Save.php
            ├── etc
            │   ├── adminhtml
            │   │   └── menu.xml
            │   ├── db_schema.xml
            │   └── module.xml
            ├── Model
            │   ├── ResourceModel
            │   │   └── Saloon
            │   │       ├── Collection.php
            │   │       └── Entity.php
            │   └── SaloonManagement.php
            ├── Setup
            │   └── InstallSchema.php
            ├── view
            │   └── adminhtml
            │       └── layout
            │           └── saloonchain_saloon_index.xml
            └── registration.php

 

 

Set Up Your Module

  1. Create the Module Directory
app/code/Nipuna/SaloonChain 
  1. Register the Module
app/code/Nipuna/SaloonChain/registration.php
<?php
use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(
    ComponentRegistrar::MODULE,
    'Nipuna_SaloonChain',
    __DIR__
);
  1. Declare the Module
app/code/Nipuna/SaloonChain/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="Nipuna_SaloonChain" />
</config>
  1. Define the Database Schema
app/code/Nipuna/SaloonChain/etc/db_schema.xml 
<?xml version="1.0"?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.magento.com/xml/schema/db" xsi:schemaLocation="http://www.magento.com/xml/schema/db ../db_schema.xsd">
    <table name="nipuna_saloonchain_table" resource="default" engine="innodb" comment="Nipuna SaloonChain Table">
        <column xsi:type="int" name="entity_id" padding="10" unsigned="true" nullable="false" identity="true" comment="Entity ID"/>
        <column xsi:type="varchar" name="name" nullable="false" length="255" comment="Name"/>
        <column xsi:type="timestamp" name="created_at" nullable="false" on_update="false" default="CURRENT_TIMESTAMP" comment="Created At"/>
        <constraint xsi:type="primary" referenceId="PRIMARY">
            <column name="entity_id"/>
        </constraint>
    </table>
</schema>

Create the Model, ResourceModel, and Collection

  1. Model Class
<?php
namespace Nipuna\SaloonChain\Model;

use Magento\Framework\Model\AbstractModel;
use Nipuna\SaloonChain\Model\ResourceModel\Entity as ResourceModel;

class Entity extends AbstractModel
{
    protected function _construct()
    {
        $this->_init(ResourceModel::class);
    }
}
  1. ResourceModel Class
 app/code/Nipuna/SaloonChain/Model/ResourceModel/Entity.php
<?php
namespace Nipuna\SaloonChain\Model\ResourceModel;

use Magento\Framework\Model\ResourceModel\Db\AbstractDb;

class Entity extends AbstractDb
{
    protected function _construct()
    {
        $this->_init('nipuna_saloonchain_table', 'entity_id');
    }
}
  1. Collection Class
app/code/Nipuna/SaloonChain/Model/ResourceModel/Entity/Collection.php 
<?php
namespace Nipuna\SaloonChain\Model\ResourceModel\Entity;

use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use Nipuna\SaloonChain\Model\Entity as Model;
use Nipuna\SaloonChain\Model\ResourceModel\Entity as ResourceModel;

class Collection extends AbstractCollection
{
    protected function _construct()
    {
        $this->_init(Model::class, ResourceModel::class);
    }
}

Implement CRUD Operations

1. Create Controller Actions for CRUD Operations

  • Index Action
app/code/Nipuna/SaloonChain/Controller/Adminhtml/Saloon/Index.php
<?php
namespace Nipuna\SaloonChain\Controller\Adminhtml\Saloon;

use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;

class Index extends Action
{
    protected $resultPageFactory;

    public function __construct(Action\Context $context, PageFactory $resultPageFactory)
    {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
    }

    public function execute()
    {
        $resultPage = $this->resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->prepend(__('Saloon Management'));
        return $resultPage;
    }

    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('Nipuna_SaloonChain::saloon');
    }
}
  •  Edit Action
app/code/Nipuna/SaloonChain/Controller/Adminhtml/Saloon/Edit.php 
<?php
namespace Nipuna\SaloonChain\Controller\Adminhtml\Saloon;

use Magento\Backend\App\Action;
use Magento\Framework\View\Result\PageFactory;

class Edit extends Action
{
    protected $resultPageFactory;

    public function __construct(Action\Context $context, PageFactory $resultPageFactory)
    {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
    }

    public function execute()
    {
        $resultPage = $this->resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->prepend(__('Edit Saloon'));
        return $resultPage;
    }

    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('Nipuna_SaloonChain::saloon');
    }
}
  • Save Action
app/code/Nipuna/SaloonChain/Controller/Adminhtml/Saloon/Save.php 
<?php
namespace Nipuna\SaloonChain\Controller\Adminhtml\Saloon;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\Exception\LocalizedException;
use Nipuna\SaloonChain\Model\SaloonFactory;

class Save extends Action
{
    protected $dataPersistor;
    protected $saloonFactory;

    public function __construct(Context $context, DataPersistorInterface $dataPersistor, SaloonFactory $saloonFactory)
    {
        $this->dataPersistor = $dataPersistor;
        $this->saloonFactory = $saloonFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $postData = $this->getRequest()->getPostValue();
        $resultRedirect = $this->resultRedirectFactory->create();

        if ($postData) {
            $model = $this->saloonFactory->create();
            $id = $this->getRequest()->getParam('saloon_id');
            if ($id) {
                $model->load($id);
            }
            $model->setData($postData);
            try {
                $model->save();
                $this->messageManager->addSuccessMessage(__('Saloon saved successfully.'));
                $this->dataPersistor->clear('saloon');
                if ($this->getRequest()->getParam('back')) {
                    return $resultRedirect->setPath('*/*/edit', ['saloon_id' => $model->getId(), '_current' => true]);
                }
                return $resultRedirect->setPath('*/*/');
            } catch (LocalizedException $e) {
                $this->messageManager->addErrorMessage($e->getMessage());
            } catch (\Exception $e) {
                $this->messageManager->addExceptionMessage($e, __('Something went wrong while saving the saloon.'));
            }

            $this->dataPersistor->set('saloon', $postData);
            return $resultRedirect->setPath('*/*/edit', ['saloon_id' => $this->getRequest()->getParam('saloon_id')]);
        }
        return $resultRedirect->setPath('*/*/');
    }

    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('Nipuna_SaloonChain::saloon');
    }
}
  • Delete Action
app/code/Nipuna/SaloonChain/Controller/Adminhtml/Saloon/Delete.php
<?php
namespace Nipuna\SaloonChain\Controller\Adminhtml\Saloon;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Exception\LocalizedException;
use Nipuna\SaloonChain\Model\SaloonFactory;

class Delete extends Action
{
    protected $saloonFactory;

    public function __construct(Context $context, SaloonFactory $saloonFactory)
    {
        $this->saloonFactory = $saloonFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $id = $this->getRequest()->getParam('saloon_id');
        $resultRedirect = $this->resultRedirectFactory->create();
        if ($id) {
            try {
                $model = $this->saloonFactory->create();
                $model->load($id);
                $model->delete();
                $this->messageManager->addSuccessMessage(__('Saloon deleted successfully.'));
                return $resultRedirect->setPath('*/*/');
            } catch (LocalizedException $e) {
                $this->messageManager->addErrorMessage($e->getMessage());
            } catch (\Exception $e) {
                $this->messageManager->addExceptionMessage($e, __('Something went wrong while deleting the saloon.'));
            }
        }
        return $resultRedirect->setPath('*/*/');
    }

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

Summary:

In this blog, we explored the essential steps required to perform CRUD operations in Magento 2, providing a comprehensive guide for developers. We started by setting up the necessary file and folder structure for a new module, ensuring a well-organised foundation for your custom functionality.

Next, we registered the module and declared it within the Magento framework, which is a critical step for Magento to recognize and integrate your custom module. We then defined the database schema using db_schema.xml, which allows Magento to manage and interact with your custom data tables effectively.

Creating the Model, ResourceModel, and Collection classes is a crucial part of any Magento module, as these classes facilitate the interaction with the database. We demonstrated how to set up these classes to handle the basic operations on the database table.

The core part of this blog focused on implementing the CRUD operations themselves. We provided detailed examples of how to create controller actions for listing, creating, updating, and deleting records. These actions are essential for managing the lifecycle of your data within the Magento backend.

By following the steps outlined in this guide, developers can extend Magento 2’s functionality to meet specific business requirements. Implementing CRUD operations allows for robust data management, which is at the heart of many e-commerce applications. Whether you are building a custom module from scratch or enhancing existing functionality, understanding and applying these principles will help you create more dynamic and responsive Magento 2 solutions.

With this knowledge, you can confidently develop modules that handle data efficiently, contributing to a seamless user experience and more powerful administrative capabilities. Magento 2’s flexibility and extensibility make it a formidable platform, and mastering CRUD operations is a fundamental skill for any Magento developer.