CRUD Operation in Magento 2 can manage data easily in the database. In the previous tutorial, you learnedΒ how to create models, resource models, and collections in Magento 2. Now, we will learn how to perform CRUD operations with a custom module in Magento 2.
To create a CRUD operation, you do not have to enter several line codes. Magento 2 offers functions for easy handling in the database.
We will see below content for CRUD Operation with a custom module.
- Create Database
- Create Module
- Read and Display Data from the Table
- Insert Data
- Update Data
- Delete Data
Step 1:Β Create Database
We discussedΒ how to create Install Schema and Upgrade Schema in Magento 2. So you can see the tutorial and create Install Schema or Upgrade Schema. Install Schema run only one time for insert data when installing the module. If you need to add some other fields then you can create Upgrade Schema using this tutorial.
Step 2:Β Create Module
We are already learnedΒ how to create a basic module in Magento 2. We need to createΒ module.xml,Β registration.php,Β routes.xml, andΒ ControllerΒ file. You can createΒ module.xml,Β registration.php, andΒ routes.xmlΒ from this tutorial. Now we create controller fileΒ Index.phpΒ inΒ app/code/Thecoachsmb/Crud/Controller/IndexΒ with the following code.
<?php namespace Thecoachsmb\MyModule\Block; use Magento\Framework\View\Element\Template; use Thecoachsmb\MyModule\Model\ContactFactory; class Index extends Template { protected $_contactFactory; public function __construct( Template\Context $context, ContactFactory $contactFactory ) { parent::__construct($context); $this->_contactFactory = $contactFactory; } public function getData() { $contact = $this->_contactFactory->create(); $collection = $contact->getCollection(); return $collection; } }
Create template fileΒ index.phtmlΒ inΒ app/code/Thecoachsmb/MyModule/view/frontend/templates folder with the following code.
<table> <tr> <th><?= __('Name'); ?></th> <th><?= __('Email'); ?></th> <th><?= __('Contact No'); ?></th> <th><?= __('Message'); ?></th> <th><?= __('Created At'); ?></th> <th><?= __('Updated At'); ?></th> <th colspan="2"><?= __('Action'); ?></th> </tr> <?php $collectionData = $block->getData(); foreach($collectionData as $collection): ?> <tr> <td><?= $collection->getName(); ?></td> <td><?= $collection->getEmail(); ?></td> <td><?= $collection->getPhoneNo(); ?></td> <td><?= $collection->getMessage(); ?></td> <td><?= $collection->getCreatedAt(); ?></td> <td><?= $collection->getUpdatedAt(); ?></td> <td> <a href="<?= $block->getUrl('mymodule/index/edit').'id/'.$collection->getId(); ?>" class="action primary">Edit</a> </td> <td> <a href="<?= $block->getUrl('mymodule/index/delete').'?id='.$collection->getId(); ?>" class="action primary">Delete</a> </td> </tr> <?php endforeach; ?> </table>
Now. run the command for cache clean and run the URLΒ yourdomain/mymodule/index/indexΒ in your browser.
Step 4:Β Insert Data
Create controller and action for insert action. We can add the following code to theΒ index.phtmlΒ file inΒ app/code/Thecoachsmb/MyModule/view/frontend/templates folder.
<a class="action primary" href="<?= $block->getUrl('mymodule/index/insert'); ?>">Add Record</a>
Now, create controller fileΒ Insert.phpΒ inΒ app/code/Thecoachsmb/MyModule/Controller/Index folder with the following code
<?php namespace Thecoachsmb\MyModule\Controller\Index; class Insert extends \Magento\Framework\App\Action\Action { protected $_pageFactory; public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Framework\View\Result\PageFactory $pageFactory ){ $this->_pageFactory = $pageFactory; return parent::__construct($context); } public function execute() { return $this->_pageFactory->create(); } }
Create layout fileΒ mymodule_index_insert.xmlΒ inΒ app/code/Thecoachsmb/MyModule/view/frontend/layoutΒ folder with the following code.
<?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"> <referenceContainer name="content"> <block class="Thecoachsmb\MyModule\Block\Insert" name="mymodule_index_insert" template="Thecoachsmb::insertdata.phtml" /> </referenceContainer> </page>
Create block fileΒ Insert.phpΒ inΒ app/code/Thecoachsmb/MyModule/BlockΒ folder with the following code.
<?php
namespace Thecoachsmb\MyModule\Block; class Insert extends \Magento\Framework\View\Element\Template { protected $_pageFactory; protected $_postLoader; public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Framework\View\Result\PageFactory $pageFactory ){ $this->_pageFactory = $pageFactory; return parent::__construct($context); } public function execute() { return $this->_pageFactory->create(); } }
Create template fileΒ insertdata.phtmlΒ inΒ app/code/Thecoachsmb/MyModule/view/frontend/templatesΒ folder with the following code.
<?php $data = $block->getEditData(); ?>
Now, create a controller for the save action. Create fileΒ Save.phpΒ inΒ app/code/Thecoachsmb/MyModule/Controller/Index folder with the following code.
<?php
namespace Thecoachsmb\MyModule\Controller\Index;
class Save extends \Magento\Framework\App\Action\Action
{
protected $_pageFactory;
protected $_contactFactory;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $pageFactory,
\Thecoachsmb\MyModule\Model\ContactFactory $contactFactory
){
$this->_pageFactory = $pageFactory;
$this->_contactFactory = $contactFactory;
return parent::__construct($context);
}
public function execute()
{
if ($this->getRequest()->isPost()) {
$input = $this->getRequest()->getPostValue();
$postData = $this->_contactFactory->create();
if($input[‘editId’]){
$postData->load($input[‘editId’]);
$postData->addData($input);
$postData->setId($input[‘editId’]);
$postData->save();
}else{
$postData->setData($input)->save();
}
return $this->_redirect(‘mymodule/index/index’);
}
}
}
Step 5:Β Update Data
Create a controller for the edit action. Create fileΒ Edit.phpΒ inΒ app/code/Thecoachsmb/MyModule/Controller/Index folder with the following code.
<?php namespace Thecoachsmb\MyModule\Controller\Index; class Edit extends \Magento\Framework\App\Action\Action { protected $_pageFactory; protected $_request; protected $_coreRegistry; public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Framework\View\Result\PageFactory $pageFactory, \Magento\Framework\App\Request\Http $request, \Magento\Framework\Registry $coreRegistry ){ $this->_pageFactory = $pageFactory; $this->_request = $request; $this->_coreRegistry = $coreRegistry; return parent::__construct($context); } public function execute() { $id = $this->_request->getParam('id'); $this->_coreRegistry->register('editId', $id); return $this->_pageFactory->create(); } }
Create layout fileΒ mymodule_index_edit.xmlΒ inΒ app/code/Thecoachsmb/MyModule/view/frontend/layoutΒ folder with the following code.
<?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"> <referenceContainer name="content"> <block class="Thecoachsmb\MyModule\Block\Edit" name="mymodule_index_edit" template="Thecoachsmb_MyModule::insertData.phtml" /> </referenceContainer> </page>
Create block fileΒ Edit.phpΒ inΒ app/code/Thecoachsmb/MyModule/BlockΒ folder with the following code.
<?php namespace Thecoachsmb\MyModule\Block; class Edit extends \Magento\Framework\View\Element\Template { protected $_pageFactory; protected $_coreRegistry; protected $_contactLoader; public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Framework\View\Result\PageFactory $pageFactory, \Magento\Framework\Registry $coreRegistry, \Thecoachsmb\MyModule\Model\ContactFactory $contactLoader, array $data = [] ){ $this->_pageFactory = $pageFactory; $this->_coreRegistry = $coreRegistry; $this->_contactLoader = $contactLoader; return parent::__construct($context,$data); } public function execute() { return $this->_pageFactory->create(); } public function getEditData() { $id = $this->_coreRegistry->registry('editId'); $postData = $this->_contactLoader->create(); $result = $postData->load($id); $result = $result->getData(); return $result; } }
Run the command for cache clean and check the result with URLΒ yourdomain/mymodule/index/index.
Step 6:Β Delete Data
Create Controller file for the Delete data. CreateΒ Delete.phpΒ file inΒ app/code/Thecoachsmb/MyModule/Controller/Index folder with the following code.
Please share youtube link for this.
Hello Rakhi,
We have not created youtube for this. WE will definitely share after creation.
Thanks,
Sonal
please create code in add edit using ui component in magnto2