Method to Save Form Data to the Custom Table in Magento 2

In this tutorial, we will learn how to save form data in a custom table in Magento 2.

when you fill a form you need to send this form so you will click on submit button. By clicking on submit button, the data has to be stored in any table. 

To do this process you need to create a submit.php file.

Create a file:

 app\code\Module\Controller\Index\Submit.php

Code:

<?php

namespace TOH\Module\Controller\Index;

use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Meetanshi\Extension\Model\ExtensionFactory;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Action\Action;

class Submit extends Action
{
protected $resultPageFactory;
protected $extensionFactory;

public function __construct(
Context $context,
PageFactory $resultPageFactory,
ExtensionFactory $extensionFactory
)
{
$this->resultPageFactory = $resultPageFactory;
$this->extensionFactory = $extensionFactory;
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->_redirect->getRefererUrl());
return $resultRedirect;

}
}

Copy this code and paste it into your submit.php file, Now you can save your data in the database. when you fill in details in the form and click on submit button data will be saved. A message will show on the form page " Data Saved Successfully"

 

Screenshot

 

if you need any kind of help you can visit Magento Digital Agency

 

Related Products