How to Update Table Data in Magento 2
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
- Use the below code in the Showdata.php file at app/code/Meetanshi/Extension/Block
1234567891011121314151617181920212223242526272829303132333435<?phpnamespace 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]);}} - Use the below code in showdata.phtml at app/code/Meetanshi/Extension/view/frontend/templates
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849<?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><?phpforeach ($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}?> - Use the below code in the Index.php file at app/code/Meetanshi/Extension/Controller/Index
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354<?phpnamespace 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;}}} - Paste the below code in the Form.php file at app/code/Meetanshi/Extension/Block
123456789101112131415161718192021222324252627282930<?phpnamespace 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);}} - Use the below code in the form.phtml file at app/code/Meetanshi/Extension/view/frontend/templates
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465<?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"><?phpif ($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> - Use the below code in the Submit.php file at app/code/Meetanshi/Extension/Controller/Index
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748<?phpnamespace 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.
Feel free to ask a question regarding this solution in the Comments section below.
I would be happy to help you.
Do share the solution with Magento Community via social media.
Thank you.
Jignesh Parmar
An expert in his field, Jignesh is the team leader at Meetanshi and a certified Magento developer. His passion for Magento has inspired others in the team too. Apart from work, he is a cricket lover.
16 Comments
When i click edit btn and the url is “http://localhost/magento/sample/helloworld/edit/id/1”, it shows 404 not found
Hello Tuan,
Please make sure, you’ve created the controller and if you already have created the controller then you need to check after caching.
Thank You
plz help how to insert data in to custom table from form data
Hello Jeet,
You can refer this blog to save form data:
https://meetanshi.com/blog/save-form-data-to-custom-table-in-magento-2/
Thank You
This error occur on last stage everything working properly
1 exception(s):
Exception #0 (Magento\Framework\Exception\RuntimeException): Type Error occurred when creating object: Meetanshi\Extension\Controller\Index\index\Interceptor, Argument 1 passed to Meetanshi\Extension\Controller\Index\Index::__construct() must implement interface Magento\Framework\UrlInterface, instance of Magento\Framework\App\Action\Context given, called in /var/www/html/magento/generated/code/Meetanshi/Extension/Controller/Index/index/Interceptor.php on line 14
Exception #0 (Magento\Framework\Exception\RuntimeException): Type Error occurred when creating object: Meetanshi\Extension\Controller\Index\index\Interceptor, Argument 1 passed to Meetanshi\Extension\Controller\Index\Index::__construct() must implement interface Magento\Framework\UrlInterface, instance of Magento\Framework\App\Action\Context given, called in /var/www/html/magento/generated/code/Meetanshi/Extension/Controller/Index/index/Interceptor.php on line 14
Hello Prasad,
Please run the below command to resolve the mentioned issue:
php bin/magento setup:di:compile
Thank You
Please guide us to add multiple file upload in catalog product admin page(i.e product attachment file).
thanks
I eagerly waiting for your responce.
Hello Parwez,
We will post the solution in the future.
Do subscribe to Meetanshi’s blog posts to get notified for the same.
Thank You
this code will create new record into DB, it doesn’t edit.
Hello Nguyen,
You just need to follow the above steps.
As it is working properly from our end for edit too.
Thank You
This is only for inserting the data not for updating the data.
Hello Shubham,
The above code works in inserting and updating both.
Thank You
This code only for new entry not update.
Hello Mahak,
The above code is properly working from our end.
Thank You
This code is not working
Hello,
It works for us perfectly. Please try again.
Thanks