We already learned how to delete data from table in Magento 2.
Now, if you want to update table data in Magento 2, do follow the below post.
Once you add the record to a table, it often requires updating that data due to some reason. In that situation, it is not a good practice to delete that record and add it again. Moreover, that’s time-consuming and frustrating too.
To overcome this kind of situation, use this method to update table data in Magento 2 store and directly update the record by clicking on the ‘edit’ button.
Method to Update Table Data in Magento 2
1. Use the below code in the Showdata.php file at app/code/Meetanshi/Extension/Block
<?php
namespace Meetanshi\Extension\Block;
use Magento\Framework\View\Element\Template;
use Magento\Backend\Block\Template\Context;
use Meetanshi\Extension\Model\ResourceModel\Extension\CollectionFactory;
class Showdata extends Template
{
public $collection;
public function __construct(Context $context, CollectionFactory $collectionFactory, array $data = [])
{
$this->collection = $collectionFactory;
parent::__construct($context, $data);
}
public function getCollection()
{
return $this->collection->create();
}
public function getDeleteAction()
{
return $this->getUrl('extension/index/delete', ['_secure' => true]);
}
public function getEditAction()
{
return $this->getUrl('extension/index/index', ['_secure' => true]);
}
}
2. Use the below code in showdata.phtml at app/code/Meetanshi/Extension/view/frontend/templates
<?php
$collection = $block->getCollection();
if ($collection->count()) {
?>
<div class="table-wrapper orders-history">
<table class="data table table-order-items history" id="my-orders-table">
<caption class="table-caption"><?php echo __('Grid Record') ?></caption>
<thead>
<tr>
<th scope="col" class="col id"><?php echo __('ID') ?></th>
<th scope="col" class="col name"><?php echo __('Name') ?></th>
<th scope="col" class="col email"><?php echo __('Email') ?></th>
<th scope="col" class="col telephone"><?php echo __('Telephone') ?></th>
<th scope="col" class="col createat"><?php echo __('Created At') ?></th>
<th scope="col" class="col action"><?php echo __('Action') ?></th>
</tr>
</thead>
<tbody>
<?php
foreach ($collection as $item): ?>
<tr>
<td data-th="<?= $block->escapeHtml(__('ID')) ?>" class="col id">
<?php echo $item->getId() ?>
</td>
<td data-th="<?= $block->escapeHtml(__('Name')) ?>" class="col name">
<?php echo $item->getName() ?>
</td>
<td data-th="<?= $block->escapeHtml(__('Email')) ?>" class="col email">
<?php echo $item->getEmail() ?>
</td>
<td data-th="<?= $block->escapeHtml(__('Telephone')) ?>" class="col telephone">
<?php echo $item->getTelephone() ?>
</td>
<td data-th="<?= $block->escapeHtml(__('Created At')) ?>"
class="col title"><?php echo date('Y-m-d', strtotime($item->getCreatedAt())); ?>
</td>
<td data-th="<?= $block->escapeHtml(__('Action')) ?>" class="col delete">
<a href="<?php echo $block->getDeleteAction() . 'id/' . $item->getId(); ?>"><?php echo __('Delete') ?></a>
<a style="margin-left: 9px"
href="<?php echo $block->getEditAction() . 'id/' . $item->getId(); ?>"><?php echo __('Edit') ?></a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php
}
?>
3. Use the below code in the Index.php file at app/code/Meetanshi/Extension/Controller/Index
<?php
namespace Meetanshi\Extension\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\UrlInterface;
use Magento\Framework\View\Result\PageFactory;
use Meetanshi\Extension\Model\ExtensionFactory;
class Index extends Action
{
protected $resultPageFactory;
private $extensionFactory;
private $url;
public function __construct(UrlInterface $url, ExtensionFactory $extensionFactory, Context $context, PageFactory $resultPageFactory)
{
parent::__construct($context);
$this->resultPageFactory = $resultPageFactory;
$this->extensionFactory = $extensionFactory;
$this->url = $url;
}
public function execute()
{
if ($this->isCorrectData()) {
return $this->resultPageFactory->create();
} else {
$this->messageManager->addErrorMessage(__("Record Not Found"));
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
$resultRedirect->setUrl($this->url->getUrl('extension/index/showdata'));
return $resultRedirect;
}
}
public function isCorrectData()
{
if ($id = $this->getRequest()->getParam("id")) {
$model = $this->extensionFactory->create();
$model->load($id);
if ($model->getId()) {
return true;
} else {
return false;
}
} else {
return true;
}
}
}
4. Paste the below code in the Form.php file at app/code/Meetanshi/Extension/Block
<?php
namespace Meetanshi\Extension\Block;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\View\Element\Template;
use Meetanshi\Extension\Model\ExtensionFactory;
class Form extends Template
{
private $extensionFactory;
public function __construct(ExtensionFactory $extensionFactory, Context $context, array $data = [])
{
parent::__construct($context, $data);
$this->extensionFactory = $extensionFactory;
}
public function getFormAction()
{
return $this->getUrl('extension/index/submit', ['_secure' => true]);
}
public function getAllData()
{
$id = $this->getRequest()->getParam("id");
$model = $this->extensionFactory->create();
return $model->load($id);
}
}
5. Use the below code in the form.phtml file at app/code/Meetanshi/Extension/view/frontend/templates
<?php
$data = $block->getAllData();
$name = '';
$email = '';
$telephone = '';
if ($data->getId()) {
$name = $data->getName();
$email = $data->getEmail();
$telephone = $data->getTelephone();
}
?>
<div class="row">
<div class="col-md-8">
<form name="addData" method="post" id="addData" class="form"
action="<?php echo $this->getFormAction(); ?>"
data-hasrequired="<?= $block->escapeHtmlAttr(__('* Required Fields')) ?>"
data-mage-init='{"validation":{}}'>
<fieldset class="fieldset">
<legend class="legend"><span><?= $block->escapeHtmlAttr(__('Fill Detail')) ?></span></legend>
<fieldset class="fieldset row">
<?php
if ($data->getId()) {
?>
<input type="hidden" name="id" value="<?php echo $data->getId(); ?>">
<?php
} ?>
<div class="fields col-md-6">
<div class="field name required">
<label class="label" for="title"><span><?= $block->
escapeHtmlAttr(__('Name')) ?></span></label>
<div class="control">
<input name="name" id="name" title="Name" value="<?php echo $name ?>" class="input-text"
type="text"
data-validate="{required:true, 'validate-alphanum-with-spaces':true}">
</div>
</div>
<div class="field name required">
<label class="label" for="title"><span><?= $block->
escapeHtmlAttr(__('Email')) ?></span></label>
<div class="control">
<input name="email" id="email" title="Email" value="<?php echo $email; ?>"
class="input-text" type="text"
data-validate="{required:true, 'validate-email':true}">
</div>
</div>
<div class="field name required">
<label class="label" for="title"><span><?= $block->escapeHtmlAttr(__('Telephone')) ?></span></label>
<div class="control">
<input name="telephone" id="telephone" title="Telephone"
value="<?php echo $telephone; ?>" class="input-text"
type="text" data-validate="{required:true}">
</div>
</div>
</div>
</fieldset>
</fieldset>
<div class="actions-toolbar">
<div class="primary">
<button type="submit" class="action submit primary" title="Save"><span><?= $block->
escapeHtmlAttr(__('Save')) ?></span></button>
</div>
</div>
</form>
</div>
</div>
6. Use the below code in the Submit.php file at app/code/Meetanshi/Extension/Controller/Index
<?php
namespace Meetanshi\Extension\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\UrlInterface;
use Magento\Framework\View\Result\PageFactory;
use Meetanshi\Extension\Model\ExtensionFactory;
class Submit extends Action
{
protected $resultPageFactory;
protected $extensionFactory;
private $url;
public function __construct(
UrlInterface $url,
Context $context,
PageFactory $resultPageFactory,
ExtensionFactory $extensionFactory
)
{
$this->resultPageFactory = $resultPageFactory;
$this->extensionFactory = $extensionFactory;
$this->url = $url;
parent::__construct($context);
}
public function execute()
{
try {
$data = (array)$this->getRequest()->getPost();
if ($data) {
$model = $this->extensionFactory->create();
$model->setData($data)->save();
$this->messageManager->addSuccessMessage(__("Data Saved Successfully."));
}
} catch (\Exception $e) {
$this->messageManager->addErrorMessage($e, __("We can\'t submit your request, Please try again."));
}
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
$resultRedirect->setUrl($this->url->getUrl('extension/index/showdata'));
return $resultRedirect;
}
}
Once you’ve set the above code, the ‘Edit’ action column will be added to the table as shown below.

The edit form will be open after clicking on the ‘Edit’ button.

Once you update the data, it shows a message that notifies you a message as shown below.

Done!
Also read: Alternative to Magento 2 Deprecated Load, Save and Delete Methods.
Do share the solution with Magento Community via social media.
Thank you.
Read more: